0

カスタム注釈があり、実行時にこの注釈のすべてのクラスをスキャンしたいと考えています。これを行う最善の方法は何ですか?私は春を使用していません。

4

2 に答える 2

3

Reflections Libraryを使用して、最初にクラス名を決定し、次に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 に答える