Java 8でGetAnnotatedParametertype()から汎用型情報を取得する方法
-
21-12-2019 - |
質問
getAnnotatedParameterTypes()
は、一般的なタイプではなく、RAWを保持しているAnnotatedType
sの配列を返します。例えば:
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()]
.
私はそれが修正が必要なバグであり、上記のバグレポートに続いているバグです。
所属していません StackOverflow