简体   繁体   English

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

[英]How to scan classes for custom Annotations?

I have my custom annotation and I want to scan all the classes for this annotation at runtime. 我有我的自定义批注,我想在运行时扫描此批注的所有类。 What is the best way to do this? 做这个的最好方式是什么? I'm not using Spring. 我没有使用Spring。

You could use the Reflections Library to determine the class names first and then use getAnnotations to check for the annotation: 您可以使用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());
     }
   }
}     

You might get annotations from the class using getClass().getAnnotations() or ask for a particular annotation if you don't want to loop over the results of the previous. 您可以使用getClass().getAnnotations()从类中获取批注,或者如果您不想遍历前一个的结果,则要求提供特定的批注。 In order for the annotation to appear on the result it's retention must be RUNTIME. 为了使注释出现在结果中,其保留时间必须为RUNTIME。 For example (not strictly correct): 例如(不完全正确):

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

Check the Javadoc: Class#getAnnotation(Class) 检查Javadoc: Class#getAnnotation(Class)

And after that your class should be annotated like this: 之后,您的班级应该这样注释:

@MyAnnotation public class MyClass {}    

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

相关问题 如何扫描类的注解? - How to scan classes for annotations? 如何使用反射库 java 仅在特定类中扫描方法中的注释? - How to scan for annotations in methods only in specific classes using reflection library java? 注释配置的框架(即Tomcat,Hibernate)如何扫描类路径中的所有类以进行注释? - How do annotation-configured frameworks (ie. Tomcat, Hibernate) scan all classes in the classpath for annotations? 如何使用 ASM 扫描字段和方法注释? - how to scan field&method annotations with ASM? 从Maven插件扫描自定义的带注释的类 - Scan custom annotated classes from maven plugin 使用自定义注释,如何使用 - Uses of custom annotations, how to 如何通过使用 spring 功能扫描所有类来检测和处理自定义注释 - How to detect and process Custom annotations by scanning all classes using spring features 从maven自定义插件进行编译之前,如何在当前项目中扫描类? - How to scan for classes in current project before compilation from maven custom plugin? 如何使用Spring扫描注释和分配给它们的值 - How to scan for Annotations and the values assigned to them Using Spring 如何扫描使用 COFOJA 编写的合同中使用的注释? - How to scan Annotations used in contracts written using COFOJA?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM