繁体   English   中英

如何扫描类以获取自定义注释?

[英]How to scan classes for custom Annotations?

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

您可以使用Reflections库来首先确定类名称,然后使用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());
     }
   }
}     

您可以使用getClass().getAnnotations()从类中获取批注,或者如果您不想遍历前一个的结果,则要求提供特定的批注。 为了使注释出现在结果中,其保留时间必须为RUNTIME。 例如(不完全正确):

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

检查Javadoc: Class#getAnnotation(Class)

之后,您的班级应该这样注释:

@MyAnnotation public class MyClass {}    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM