본문 바로가기
Java

자바 중급 2편 - 제네릭(3)

by KongJiHoon 2025. 5. 31.

1. 제네릭 메서드란

  • 특정 메서드에만 타입 매개변수를 적용해 다양한 타입을 처리할 수 있도록 만든 메서드이다.
public static <T> T genericMethod(T t) {
    System.out.println("generic print: " + t);
    return t;
}

✅ 제네릭 메서드 선언 방식

  • public static <T> T methodName(T t) 형태로 사용합니다.
  • 반환 타입 앞에 <T>를 선언해야 합니다.

✅ 타입 인자 전달 방법

  • 명시적으로 전달: GenericMethod.<Integer>genericMethod(10)
  • 타입 추론 사용: GenericMethod.genericMethod(10) → 자바가 자동 추론

✅ 타입 제한 (bounded type parameter)

public static <T extends Number> T numberMethod(T t) {
    System.out.println("bound print: " + t);
    return t;
}
  • T extends Number로 숫자 타입만 받을 수 있게 제한한다.
  • Integer, Double, Long 등만 사용 가능하며 String은 컴파일 에러 발생.

GenericMethod 클래스

public class GenericMethod {
    public static Object objMethod(Object obj) {
        System.out.println("object print: " + obj);
        return obj;
    }

    public static <T> T genericMethod(T t) {
        System.out.println("generic print: " + t);
        return t;
    }

    public static <T extends Number> T numberMethod(T t) {
        System.out.println("bound print: " + t);
        return t;
    }
}

MethodMain1

public class MethodMain1 {
    public static void main(String[] args) {
        Integer i = 10;
        Object object = GenericMethod.objMethod(i);

        System.out.println("명시적 타입 인자 전달");
        Integer result = GenericMethod.<Integer>genericMethod(i);
        Integer integerValue = GenericMethod.<Integer>numberMethod(10);
        Double doubleValue = GenericMethod.<Double>numberMethod(20.0);

        System.out.println("타입 추론");
        Integer result2 = GenericMethod.genericMethod(i);
        Integer integerValue2 = GenericMethod.numberMethod(10);
        Double doubleValue2 = GenericMethod.numberMethod(20.0);
    }
}

제네릭 타입 vs 제네릭 메서드 우선순위

public class ComplexBox<T extends Animal> {
    private T animal;

    public void set(T animal) {
        this.animal = animal;
    }

    public <T> T printAndReturn(T t) {
        System.out.println("animal.className: " + animal.getClass().getName());
        System.out.println("t.className: " + t.getClass().getName());
        return t;
    }
}

주의 사항

  • 클래스의 제네릭 타입 <T extends Animal>와 메서드의 제네릭 타입 <T>다른 변수.
  • 메서드에서 <T>를 다시 선언하면 제네릭 메서드의 타입이 우선순위가 된다
  • 따라서 메서드 내의 TObject로 처리되어 getName() 같은 메서드는 사용할 수 없다.
public class ComplexBox<T extends Animal> {
    ...
    public <Z> Z printAndReturn(Z z) {
        return z; // 타입 명확히 분리해 혼동 방지
    }
}

정리

구분 네릭 타입 제네릭 메서드
선언 위치 클래스 또는 인터페이스 메서드 내부
선언 방식 class Box T method(T t)
타입 인자 결정 시점 객체 생성 시점 메서드 호출 시점
static 사용 불가 가능

'Java' 카테고리의 다른 글

자바 중급 2편 - ArrayList(1)  (0) 2025.07.07
자바 중급 2편 - 제네릭(4)  (0) 2025.06.01
자바 중급 2편 - 제네릭(2)  (0) 2025.05.15
자바 중급 2편 - 제네릭(1)  (0) 2025.05.11
Java 중급 1 - 예외처리(4)  (0) 2025.05.10