일반 정적 메서드가 있고 삽입 된 실제 제네릭 형식의 클래스 개체를 반환 할 싶습니다.정적 메서드에서 실제 제네릭 형식의 클래스 개체 가져 오기
나는이처럼 시도 :
@SuppressWarnings("unchecked")
public static <T> Class<T> getClassType() {
Method thisMethod;
try {
thisMethod = CommonTools.class.getMethod("getClass", new Class<?>[0]);
} catch (Exception ex) {
//ErrorLog.error(ex.getMessage(), ex);
return null;
}
Type returnType = thisMethod.getGenericReturnType();
Type tType = returnType.getClass().getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) tType;
Class<T> clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
return clazz;
}
이에 대한 나의 영감이 거기에, 구글 코드 모르핀 라이브러리에서 발견 그들은이 같은 것을 사용하고 있습니다 :
(((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]))
내 코드의 차이 그리고 그 코드는 클래스에서 제네릭 타입을 찾기 위해 그것을 호출한다는 것입니다 - 메소드에서 사용되기를 바랍니다.
내 코드가 작동하지 않고 클래스 변환 라인에 속합니다.
정적 메서드에서 현재 제네릭 형식을 가져 오는 방법에 대한 아이디어가 있습니까?
감사합니다.
왜 이 2 회인가 public static이어야합니다. 내가 잘못하지 않은 경우 getClassType(). –
그리고 T가 제네릭 매개 변수라는 것을 알기보다는 메서드가 어떻게해야합니까? – ondra