0

我有我的自定义注释,我想在运行时扫描所有类以查找此注释。做这个的最好方式是什么?我没有使用弹簧。

4

2 回答 2

3

您可以使用反射库首先确定类名,然后使用getAnnotations检查注释:

Reflections reflections = new Reflections("org.package.foo");

Set<Class<? extends Object>> allClasses = 
                 reflections.getSubTypesOf(Object.class);


for (Class clazz : allClasses) {
   Annotation[] annotations = clazz.getAnnotations();

   for (Annotation annotation : annotations) {
     if (annotation instanceof MyAnnotation) {
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
     }
   }
}     
于 2013-01-10T02:03:32.200 回答
0

getClass().getAnnotations()如果您不想循环遍历先前的结果,您可能会使用或要求特定注释从类中获取注释。为了使注释出现在结果中,它的保留时间必须是 RUNTIME。例如(不完全正确):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {}

检查 Javadoc:Class#getAnnotation(Class)

之后,您的课程应该像这样注释:

@MyAnnotation public class MyClass {}    
于 2013-01-10T02:03:54.663 回答