我不明白的下面的代碼的行爲: https://gist.github.com/tomaszalusky/3e3777b4fd0c6096f3f707bb19b50b52 - 見嵌入式:對於嵌套類型,爲什麼對泛型類型參數的註釋不可見?
import java.lang.reflect.*;
import java.util.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class AnnotationOnTypeArgument {
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD,ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {
}
interface Nested<T> {
}
Toplevel<@Anno Integer> toplevel;
Nested<@Anno Integer> nested;
public static void main(String[] args) throws Exception {
print(AnnotationOnTypeArgument.class.getDeclaredField("toplevel"));
print(AnnotationOnTypeArgument.class.getDeclaredField("nested"));
}
private static void print(Field field) {
AnnotatedType annotatedType = field.getAnnotatedType();
AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType)annotatedType;
ParameterizedType parameterizedType = (ParameterizedType)annotatedParameterizedType.getType();
AnnotatedType argType = annotatedParameterizedType.getAnnotatedActualTypeArguments()[0];
System.out.printf("field %s%ntype=%s%nannotatedType=%s%nannotations=%s%ntype=%s%n%n",
field.getName(), parameterizedType, argType, Arrays.asList(argType.getDeclaredAnnotations()), argType.getType());
}
}
interface Toplevel<T> {
}
編輯:實際的結果是:
field toplevel
type=Toplevel<java.lang.Integer>
annotatedType=su[email protected]1540e19d
annotations=[@AnnotationOnTypeArgument$Anno()]
type=class java.lang.Integer
field nested
type=AnnotationOnTypeArgument.AnnotationOnTypeArgument$Nested<java.lang.Integer>
annotatedType=su[email protected]677327b6
annotations=[]
type=class java.lang.Integer
爲什麼宣佈註釋對類型參數的數組周圍類型嵌套時爲空?我希望有一個元素,就像頂級類型一樣。我很感謝任何基於JLS的解釋。
在JDK8u101(http://compilejava.net),較老的JDK8和Eclipse中一致發生。
謝謝!
我認爲,我們可以追蹤它回到['AnnotatedTypeFactory' ,第105行](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/reflect/annotation/AnnotatedTypeFactory.java#105)嵌套參數化類型是無條件地視爲(非'靜態')內部類(不同於可定義類型,前面7行)。實際上,詢問一個'ParametertrizedType'是否是'static',不是直接的... – Holger