<分区>
当注释类型是嵌套的通用接口(interface)时,似乎无法通过反射访问 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()));
}
}
上述代码的预期输出是
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
接口(interface)的每次使用中都可以正确检索注释。但是,在每次使用 Entry
接口(interface)时,无论是字段、返回类型还是参数,注释都会丢失。我对此的唯一解释是 Entry
接口(interface)嵌套在 Map
接口(interface)中。
我在 win64 上最新的 oracle JDK (8u121) 上运行了上面的例子。我做错了什么或者这可能是一个错误?
为了便于阅读,我的注释是嵌套的。将其设为顶级界面不会改变任何内容。