[英]Finding an annotation in a list
In my code, I may have annotation defined on methods or fields so what I'm doing is checking both the methods and fields in the class and I store all annotations in a separate list. 在我的代码中,我可能在方法或字段上定义了注释,所以我正在做的是检查类中的方法和字段,并将所有注释存储在单独的列表中。
Then later I have a method called getAnnotation. 然后我有一个名为getAnnotation的方法。
Annotation getAnnotation(Class annotationClass) {
for (Annotation annotation : annotations) {
if (annotation.getClass().equals(annotationClass)) {
return annotation;
}
}
return null;
}
And I call it like this: 我称之为:
Annotation annotation = getAnnotation(MyAnnotation.class);
The problem is that the getAnnotation method does not match up the class names. 问题是getAnnotation方法与类名不匹配。 When I debug I see that the annotations are showing as proxy objects. 当我调试时,我看到注释显示为代理对象。 How can I find the specific annotation that I want in this case? 在这种情况下,如何找到我想要的特定注释?
TIA TIA
I define the map like this: 我像这样定义地图:
Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>(4);
I populated the Map like this: 我像这样填充了地图:
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
annotations.put(annotation.getClass(), annotation);
}
You'd better populate a Map<Class<? extends Annotation>, Annotation>
你最好填充一个Map<Class<? extends Annotation>, Annotation>
Map<Class<? extends Annotation>, Annotation>
- that way the lookup will be O(1), and you won't care if its a proxy or not. Map<Class<? extends Annotation>, Annotation>
- 这样查找将是O(1),你不会关心它是否是代理。
Yay! 好极了! I figured it out. 我想到了。 The Annotation object has an "annotationType()" method to return the real class name. Annotation对象有一个“annotationType()”方法来返回实际的类名。
So the code for anyone interested would look like this: 所以感兴趣的人的代码看起来像这样:
Map, Annotation> annotations = new HashMap, Annotation>(4); Map,Annotation> annotations = new HashMap,Annotation>(4);
Annotation[] annos = method.getAnnotations();
for (Annotation anno : annos) {
annotations.put(anno.annotationType(), annotation);
}
Then the class matching works fine. 然后类匹配工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.