アノテーションのアノテーションを取得する3つの方法
Java5以降アノテーションが適用できるんだけども、アノテーションを付加しすぎると煩雑になってしまう。
そこで、アノテーションのユーティリティーとして
アノテーションに対してアノテーションを複数付加する。で、それをソースにひとつ付加するようにすると煩雑さが解消される。
ってことでアノテーションのアノテーションを取得するやり方を3つ作成
欠点として、アノテーションに付加したアノテーションは値を個別に設定することが
できない問題がある。
ソースはこんな感じ。
import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * * @author kensir0u * */ @SuppressWarnings("all") public class AnnoAnno { public static void main(String args[]) throws Exception { // アノテーションクラスから一覧取得 printDisplay(Retention.class); Retention anno = (Retention) Proxy.newProxyInstance(Thread .currentThread().getContextClassLoader(), new Class[] { Retention.class }, new InvocationHandler() { public Object invoke(Object o, Method m, Object[] args) throws Throwable { return null; } }); // アノテーションインスタンスから一覧取得 printDisplay(anno); // アノテーションクラスを指定して取得 Retention ar = Retention.class.getAnnotation(Retention.class); System.out.println(ar.value()); Target at = Retention.class.getAnnotation(Target.class); System.out.println(at.value()[0]); } private static void printDisplay(Class<? extends Annotation> c) throws Exception { // アノテーションのインスタンスを取得 Annotation[] anno = c.getDeclaredAnnotations(); for (int i = 0; i < anno.length; i++) { // インターフェースのアノテーションを取得 Class[] ci = anno[i].getClass().getInterfaces(); for (int j = 0; j < ci.length; j++) { // アノテーションのクラスを取得 Class class1 = ci[j]; // アノテーションのメソッド一覧を取得 Method[] m = class1.getDeclaredMethods(); for (int k = 0; k < m.length; k++) { Method method = m[k]; // 戻り値を確認 Class ret = method.getReturnType(); // 配列の場合 if (ret.isArray()) { Object o = method.invoke(anno[i], new Object[0]); for (int l = 0; l < Array.getLength(o); l++) { System.out.println(Array.get(o, l)); } // 配列以外 } else { System.out.println(method .invoke(anno[i], new Object[0])); } } } } } private static void printDisplay(Annotation anno) throws Exception { // アノテーションクラス配列を取得 Class[] ci = anno.getClass().getInterfaces(); for (int j = 0; j < ci.length; j++) { // アノテーションのインスタンス配列を取得 Annotation ano[] = ci[j].getAnnotations(); for (int i = 0; i < ano.length; i++) { // アノテーションのインスタンスを取得 Annotation annotation = ano[i]; // アノテーションのクラス配列を取得 Class ac[] = annotation.getClass().getInterfaces(); for (int n = 0; n < ac.length; n++) { Class class1 = ac[n]; // アノテーションのメソッド一覧を取得 Method[] m = class1.getDeclaredMethods(); for (int k = 0; k < m.length; k++) { Method method = m[k]; // 戻り値を確認 Class ret = method.getReturnType(); // 配列の場合 if (ret.isArray()) { Object o = method.invoke(annotation, new Object[0]); for (int l = 0; l < Array.getLength(o); l++) { System.out.println(Array.get(o, l)); } // 配列以外 } else { System.out.println(method.invoke(annotation, new Object[0])); } } } } } } }