当带注释的类型是嵌套的泛型接口时,似乎无法通过反射访问 TYPE_USE 注释。
请观察以下示例:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
public class LostAnnotation {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface SomeTypeAnnotation {
}
@SomeTypeAnnotation Map<String, String> map;
@SomeTypeAnnotation Entry<String, String> entry;
public static @SomeTypeAnnotation Entry<String, String> someMethod(
@SomeTypeAnnotation Map<String, String> map,
@SomeTypeAnnotation Entry<String, String> entry) {
return null;
}
public static void main(String[] args) throws Exception {
Class<LostAnnotation> clazz = LostAnnotation.class;
Method method = clazz.getMethod("someMethod", Map.class, Entry.class);
AnnotatedType[] types = method.getAnnotatedParameterTypes();
print("map field", clazz.getDeclaredField("map").getAnnotatedType());
print("map parameter", types[0]);
print("entry field", clazz.getDeclaredField("entry").getAnnotatedType());
print("entry parameter", types[1]);
print("entry return type", method.getAnnotatedReturnType());
}
static void print(String title, AnnotatedType type) {
System.out.printf("%s: %s%n", title, Arrays.asList(type.getAnnotations()));
}
}
The 预期产出上面的代码是
map field: [@LostAnnotation$SomeTypeAnnotation()]
map parameter: [@LostAnnotation$SomeTypeAnnotation()]
entry field: [@LostAnnotation$SomeTypeAnnotation()]
entry parameter: [@LostAnnotation$SomeTypeAnnotation()]
entry return type: [@LostAnnotation$SomeTypeAnnotation()]
但是,那实际产量上面的代码是
map field: [@LostAnnotation$SomeTypeAnnotation()]
map parameter: [@LostAnnotation$SomeTypeAnnotation()]
entry field: []
entry parameter: []
entry return type: []
从每次使用中都可以正确检索注释Map
界面。然而,在每次使用Entry
接口,无论是字段、返回类型还是参数,注释都会丢失。我对此的唯一解释是Entry
接口是嵌套在里面 the Map
界面。
我在 win64 上最新的 oracle JDK (8u121) 上运行了上面的示例。我做错了什么或者这可能是一个错误吗?
为了便于阅读,我的注释是嵌套的。使其成为顶级接口不会改变任何东西。