Javaでアノテーションが付与されたメソッドを取得する方法
annotationでマークされたメソッドを取得するには反射メカニズムが使用できます。
最初に注釈を取得するクラスのClassオブジェクトを取得する必要があります。クラス名.classまたはオブジェクト.getClass()メソッドを使用して取得できます。次に、ClassオブジェクトのgetMethods()メソッドを使用して、そのクラスのすべてのパブリックメソッドを取得します。次に、これらのメソッドを反復処理し、MethodオブジェクトのgetAnnotation()メソッドを使用して、メソッド上の指定された注釈を取得できます。
サンプルコードを示します。
import java.lang.reflect.Method;
public class AnnotationExample {
@MyAnnotation
public void myMethod() {
// 方法体
}
public static void main(String[] args) throws NoSuchMethodException {
Class<AnnotationExample> clazz = AnnotationExample.class;
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Method " + method.getName() + " has annotation " + annotation.value());
}
}
}
}
上記コードでは、@MyAnnotationというカスタムアノテーションを定義し、myMethod()メソッドで使用しています。mainメソッドでは、AnnotationExampleクラスの全てのメソッドをリフレクションで取得し、各メソッドに@MyAnnotationアノテーションが付いているかを調べ、付与されていればメソッド名とアノテーションの値を出力しています。
親クラスのメソッドを含むメソッドを取得するには、getDeclaredMethods() メソッドを使用します。