LoginSignup
22
23

More than 5 years have passed since last update.

Java リフレクションとアノテーションを組み合わせて使用する

Last updated at Posted at 2014-01-29

自作のAnnotationをReflectionで引っ掛けてゴニョゴニョしようとする場合、
@Retentionの設定が必要です。

@Retentionの設定は下記の三種類があります。

■ RetentionPolicy.RUNTIME
classファイルに記録され実行時に参照できる。
■ RetentionPolicy.CLASS
classファイルに記録されるが実行時には保持されない。(default)
■ RetentionPolicy.SOURCE
コンパイル時に破棄される。

よって、上記のような使い方をしたい場合はRetentionPolicy.RUNTIMEで
設定してあげれば正しい動作をしてくれます。
その他の設定にしていた場合、f.getAnnotation(CustomAnnotation.class)の結果がnullになります。

CustomAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomAnnotation {
    public String value();
}

Hoge.java

public class Hoge {
    @CustomAnnotation("a")
    private String name;

    @CustomAnnotation("b")
    private int value;

    /** ~中略~ */
}

ReflectionUtil.java

public class ReflectionUtil{

     public static void output(Object obj){
         if(obj == null){
            return null;
         }

         Field[] fieldList = obj.getClass().getDeclaredFields();

         for (Field f: fieldList) {
                f.setAccessible(true);
                String name     = f.getName();
                Object fieldObj = f.get(obj);

                // RetentionPolicy.RUNTIME以外はここがnullになります。
                if(f.getAnnotation(CustomAnnotation.class) != null){
                        CustomAnnotation element = 
                                      f.getAnnotation(CustomAnnotation.class);
                        System.out.println(element.value());
                }
         }
     }

}

Main.java

public class TestMain {

        public static void main(String[] args) {
             Hoge h = new Hoge();
             ReflectionUtil.output(h);
        }
}

まあ、初歩的な事なんだけど、メモ的に記録しておこう。

22
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
23