2010-12-30 6 views
1

리플렉션을 사용하여 수퍼 클래스에 전달 된 유형 매개 변수 값을 찾는 방법은 무엇입니까? Bar.class을 부여 예를 들어 리플렉션을 사용하여 유형 매개 변수 액세스

는, 나는 그것이 Integer.classFoo에 형식 매개 변수 T을 전달하는 방법을 찾을 수 있습니까?

public class Foo<T> { 
} 

public class Bar extends Foo<Integer> { 
} 

고마워요! 바 특정 푸를 확장하는 클래스이기 때문에

답변

1

당신은

ParameterizedType type = (ParameterizedType) Bar.class.getGenericSuperclass(); 
System.out.println(type.getRawType()); // prints; class Foo 
Type[] actualTypeArguments = type.getActualTypeArguments(); 
System.out.println(actualTypeArguments[0]); // prints; class java.lang.Integer 

이 단지 작품을 시도 할 수 있습니다. 다음과 같은 변수를 선언하면 런타임에 intFoo의 매개 변수 유형을 결정할 수 없습니다.

Foo<Integer> intFoo = new Foo<Integer>(); 
2
public class Bar extends Foo<Integer> { 

public Class getTypeClass { 
    ParameterizedType parameterizedType = 
    (ParameterizedType) getClass().getGenericSuperClass(); 
    return (Class) parameterizedtype.getActualTypeArguments()[0]; 
} 

} 

때문에 형의 삭제의,을 보장 실제 상황, 하지만 대부분의 작업을해야 위의 직접이 작업을 수행 할 수있는 방법이 없습니다.

+0

이 경우 getTypeClass() 클래스는 또는 Integer.class 클래스를 반환 할 수 있습니다. ;) –

+0

@Peter 예. 난 그냥 일반적인 방식으로 프로세스를 보여 주려고 :) –

관련 문제