ひがやすを技術ブログ

電通国際情報サービスのプログラマ

アノテーションのインスタンスの作り方

アノテーションAnnoのオブジェクトは@Annoが付与されているクラスやメソッドに対応するClassやMethodオブジェクトについてAnnotatedElement#getAnnotation(Anno.class)を呼び出すことで取得できるが、新たに生成したいことがある(かもしれない)。

そこでいろいろ試してみた。

まずこれ。

Anno anno = Anno.class.newInstance();

これはあえなくInstantiationException。

んで次はこれ。

Constructor<?>[] constructors = Anno.class.getConstructors();
System.out.println(constructors.length);

この結果は「0」。そもそもコンストラクタがないのね…。

アノテーションの実体はインターフェースなので、Proxyを使えばインスタンスを作成できます。

package examples.main;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class AnnotationExample {

    public static void main(String[] args) {
        Retention retention = (Retention) Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(),
            new Class[] { Retention.class },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
                    if (method.getName().equals("annotationType")) {
                        return Retention.class;
                    } else if (method.getName().equals("value")) {
                        return RetentionPolicy.RUNTIME;
                    }
                    return null;
                }

            });
        System.out.println(retention.annotationType());
        System.out.println(retention.value());
    }
}