反射

2013-05-16 8 views
38

を使用することによって、私は私の注釈反射

public @interface MyAnnotation { 
} 

を作成し、注釈とフィールドのリストを取得します。私は今、私はすべてのフィールドのリストを取得したい私のテストオブジェクト

public class TestObject { 

    @MyAnnotation 
    final private Outlook outlook; 
    @MyAnnotation 
    final private Temperature temperature; 
    ... 
} 

内のフィールドの上に置きますMyAnnotation

for(Field field : TestObject.class.getDeclaredFields()) 
{ 
    if (field.isAnnotationPresent(MyAnnotation.class)) 
     { 
       //do action 
     } 
} 

しかし、私のブロックのように思えるが、アクションが実行されることはありませんか、次のコードは、0

TestObject.class.getDeclaredField("outlook").getAnnotations().length; 

を返すようにフィールドには何の注釈を持っていないが、誰もが私を助け、私がやっているものを私に伝えることができますです違う?

+0

1)より早くより良いヘルプについては、[SSCCE](http://sscce.org/)を投稿。 2)文頭に大文字を入れてください。また、私はJavaのような適切な名前と、JEEやWARのような略語や頭字語のように、大文字を使います。これにより、人々は理解しやすくなり、助けやすくなります。 –

+0

[メンバ変数の注釈を取得する方法](http://stackoverflow.com/questions/4453159/how-to-get-annotations-of-a-member-variable) – fglez

答えて

54

注釈は、実行時に利用可能であるとマークする必要があります。アノテーションコードに以下を追加します。

@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 
} 
+0

正しいです。しかし、私は、注釈は実行時の使用のためだと思った。 – wrivas

+3

@wrivasすべての注釈が実行時用であるとは限りません。たとえば、 '@ SuppressWarnings'はRetentionPolicy.SOURCEです。なぜなら、特定のことについて警告を出さないコンパイラのヒントに過ぎないからです。 – Patrick

+0

注釈はソースのみ(あなたが読めるように)、コンパイル時間またはランタイム –

6
/** 
* @return null safe set 
*/ 
public static Set<Field> findFields(Class<?> classs, Class<? extends Annotation> ann) { 
    Set<Field> set = new HashSet<>(); 
    Class<?> c = classs; 
    while (c != null) { 
     for (Field field : c.getDeclaredFields()) { 
      if (field.isAnnotationPresent(ann)) { 
       set.add(field); 
      } 
     } 
     c = c.getSuperclass(); 
    } 
    return set; 
} 
+11

Apache Commonsにはこの機能があります:FieldUtils.getFieldsListWithAnnotation(...) – DBK