Java 8에서 getAnnotatedParameTertypes ()에서 일반 유형 정보를 얻는 방법은 무엇입니까?
-
21-12-2019 - |
문제
getAnnotatedParameterTypes()
는 일반적인 유형이 아닌 원시를 보유하는 AnnotatedType
의 배열을 반환하는 것처럼 보입니다.예 :
public <T> void genericMethod(T t) {
}
@Test
public void testAnnotatedTypes() throws ReflectiveOperationException {
Method method = getClass().getMethod("genericMethod", Object.class);
Type type = method.getGenericParameterTypes()[0];
assertTrue(type instanceof TypeVariable);
AnnotatedType annotatedType = method.getAnnotatedParameterTypes()[0];
// This fails; annotatedType implements only AnnotatedType
assertTrue(annotatedType instanceof AnnotatedTypeVariable);
// This fails too; type is a TypeVariable while annotatedType.getType() is
// Object.class
assertEquals(type, annotatedType.getType());
}
.
getGenericParameterTypes()
의 불일치의 이유는 무엇입니까?
해결책
이후 에 대한 버그 보고서가 고정되었습니다.
사이에는 차이가 있습니다. Method#getGenericParameterTypes()
및 Method#getAnnotatedParameterTypes()
.
전자는
를 반환하는 유형에 대해 보장합니다.공식적인 매개 변수 유형이 매개 변수화 된 유형 인 경우 유형 오브젝트 리턴 된 것은 실제 유형 매개 변수를 정확하게 반영해야합니다. 소스 코드에서 사용됩니다.
공식 매개 변수 유형이 유형 변수 또는 매개 변수 유형 인 경우, 그것은 생성됩니다. 그렇지 않으면 해결됩니다.
후자는 적어도 명확하지는 않지만 :
는 사용을 나타내는
AnnotatedType
객체의 배열을 반환합니다. 메소드 / 생성자의 공식 매개 변수 유형을 지정하는 유형 이Executable
로 표시됩니다.
getAnnotatedParameterTypes()
지우개 유형을 반환합니다 (그런 식으로 의도되지 않았을 수 있지만). 무한한 유형 변수 T
는 Object
로 지워집니다. <T extends Foo>
가있는 경우 Foo
에 지워질 것입니다.
의견은 메소드 매개 변수에서 형식 인수로부터 주석을 가져 오는 것에 대해 위의 방법이 없어야합니다. 하나는 그것이 필드에 따라 작동하는 것으로 생각할 것입니다.
public static void main(String[] args) throws Exception {
Field field = Example.class.getField("field");
AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) field
.getAnnotatedType();
System.out.println(annotatedParameterizedType
.getAnnotatedActualTypeArguments()[0].getType());
System.out.println(Arrays.toString(annotatedParameterizedType
.getAnnotatedActualTypeArguments()[0].getAnnotations()));
}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE_USE })
@interface Bar {
}
public List<@Bar String> field;
.
을 인쇄합니다
class java.lang.String
[@com.example.Example$Bar()]
.
나는 그것이 위에 링크 된 버그 보고서를 고정시키는 버그라고 생각합니다.