2010-08-20 1 views
6

서명을 기반으로 인터페이스에 메소드가 있는지 확인하고 싶습니다. 방법이 있어야한다메소드가 Java에서 콜렉션 <Foo>을 리턴하는지 확인하는 방법은 무엇입니까?

서명은 다음과 같습니다

Collection<Foo> methodName(Spam arg0, Eggs arg1, ...) 

난 후, 이름을 찾을 매개 변수와 method.getName(), method.getParameterTypes()method.getReturnType()로 각각 형식을 반환 Class.getMethods() 를 통해 방법을 찾을 수 있습니다.

하지만 Collection<Foo>을 반환하는 메서드 만 선택하고 다른 컬렉션을 반환하지 않도록 반환 값의 형식을 어떻게 비교해야합니까?

method.getReturnType().equals(Collection.class) 

(가) 위의 Foo 컬렉션을 반환하는 사람들을 위해뿐만 아니라, 컬렉션을 반환하는 모든 방법에 대한 진정한 될 것입니다.

+0

참조 http://www.artima.com/weblogs/viewpost.jsp?thread=208860 – Artefacto

+0

http://stackoverflow.co 중복 m/questions/3520057/how-can-i-learn-actual-type-generic-class-of-generic-class –

+0

이것은 중복이 아닙니다. 질문은 인스턴스화가 아닌 매개 변수화 된 반환 유형을 검사하는 방법입니다 매개 변수화 된 형식의 –

답변

8

http://download.oracle.com/javase/tutorial/reflect/member/methodType.html를 참조하십시오.

ParameterizedTypeCollection<Foo>과 같은 일반 유형에 대한 추가 정보를 제공 할 수 있습니다.

특히 getActualTypeArguments() 메서드를 사용하면 각 매개 변수의 실제 유형을 가져올 수 있습니다. 여기

ParameterizedType는 컬렉션을 나타냅니다 및 getActualTypeArguments()은 푸

를 포함하는 배열을 나타냅니다 당신은 당신의 제네릭 형식의 매개 변수 목록에이 시도 할 수

:

Type returnType = method.getGenericReturnType(); 
if (returnType instanceof ParameterizedType) { 
    ParameterizedType type = (ParameterizedType) returnType; 
    Type[] typeArguments = type.getActualTypeArguments(); 
    for (Type typeArgument : typeArguments) { 
     Class typeArgClass = (Class) typeArgument; 
     System.out.println("typeArgClass = " + typeArgClass); 
    } 
} 

출처 : http://tutorials.jenkov.com/

+0

감사합니다. 그것이 그랬고 기사는 어떻게 그리고 왜에 대해 조금 더 설명합니다. – brice

+0

[method.getTypeParameters()] (http://download.oracle.com/javase/6/docs/api/java/lang/reflect/GenericDeclaration.html)도 제대로 작동합니까? – brice

+1

Method.getTypeParameters() 메소드 자체에 대한 일반 정보를 제공합니다. Collections.unmodifiableList : 'public static 리스트 unmodifiableList (리스트 리스트) {'결과는 "T"가 포함 된 배열이됩니다. –

1

일반 유형 매개 변수는 Java에서 런타임에 유지되지 않습니다 (즉, 컴파일 타임 전용 기능). 그렇게 할 수 없습니다.

2

는 반환 할 수 public Type getGenericReturnType()라는 이름의 방법은 (가 만약의 경우)를 ParameterizedType

관련 문제