HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🌚
[New] 우기팀
/
득윤
득윤
/
❓
Java Generic
/
2️⃣
제네릭 메서드
2️⃣

제네릭 메서드

 

제네릭 메서드 (Generic Methods)

제네릭 메서드는 자신의 타입 파라미터를 가진 메서드이다. 제네릭 타입(제네릭 클래스, 제네릭 인터페이스)을 정의 할때와 비슷하지만 타입 파라미터의 스코프가 다르다. static, non-static 메서드 모두 제네릭이 될 수 있으며 제네릭 클래스의 생성자도 제네릭이 될 수 있다.
 
아래의 Util 클래스는 제네릭 메서드 compare 를 가진다.
타입 파라미터는 메서드 시그니처의 리턴타입 앞에 선언되며 메서드의 파라미터, 메서드 블럭에서 사용될 수 있다.
public class Util { public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } } public class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } public K getKey() { return key; } public V getValue() { return value; } }
 
 
이때 메서드를 호출하는 syntax 는 아래와 같다.
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same1 = Util.<Integer, String>compare(p1, p2); boolean same2 = Util.compare(p1, p2);
컴파일러의 타입 추론기능으로 인해 제네릭 메서드에서 타입 인자를 생략 할 수 있다.
자세한 내용은 타입추론 섹션을 참고하자.

메서드 시그니처

자바의 메서드 시그니처는 메서드 오버로딩을 판단하는 기준이 된다.
메서드 시그니처는 메서드 이름 + 메서드 파라미터의 타입, 순서로 리턴 타입은 포함하지 않는다.
public interface signature { int doSomething(); void doSomething(); }
메서드 시그니처가 겹쳐서 오버로딩이 되지 않고 컴파일 에러가 발생한다. 'doSomething()' is already defined in 'signature’
 
추가로 제네릭 메서드의 타입 파라미터는 메서드 시그니처에 포함되지 않는다.
public interface signature { <T> int doSomething(); int doSomething(); }
메서드 시그니처가 겹쳐서 오버로딩이 되지 않고 컴파일 에러가 발생한다. 'doSomething()' clashes with 'doSomething()'; both methods have same erasure
컴파일 에러의 내용이 다르다! 자세한 내용은 erasure 섹션을 참고하자.