簡體   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