javaによるアノテーションの読み込み

反射を使って注釈つきの内容すべてを読み取ることができます。

まず、対象クラスのClassオブジェクトを取得します。その後、ClassオブジェクトのgetAnnotations()メソッドを使用して、このクラスのすべての注釈を取得します。次にClassオブジェクトのgetDeclaredMethods()メソッドを使用して、このクラスのすべてのメソッドを取得します。その後、これらのメソッドを反復処理し、MethodオブジェクトのgetAnnotations()メソッドを使用して、各メソッドの注釈を取得します。

以下にサンプルコードをを示します。

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class AnnotationReader {
public static void main(String[] args) {
Class<MyClass> clazz = MyClass.class;
// 读取类上的注解
Annotation[] classAnnotations = clazz.getAnnotations();
for (Annotation annotation : classAnnotations) {
System.out.println(annotation);
}
// 读取方法上的注解
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Annotation[] methodAnnotations = method.getAnnotations();
for (Annotation annotation : methodAnnotations) {
System.out.println(annotation);
}
}
}
}
// 带有注解的类
@MyAnnotation("class annotation")
class MyClass {
// 带有注解的方法
@MyAnnotation("method annotation")
public void myMethod() {
// ...
}
}
// 自定义注解
@interface MyAnnotation {
String value();
}

このコードを実行すると、結果は次のようになります。

@MyAnnotation(value=class annotation)
@MyAnnotation(value=method annotation)

注釈付きのすべてのコンテンツを読み取できます。なお、上記のコードはクラスとメソッドの注釈のみを読み取ります。 フィールドの注釈も読み取りたい場合は、ClassオブジェクトのgetDeclaredFields()メソッドを使用してフィールド配列を取得し、フィールド配列を反復処理し、FieldオブジェクトのgetAnnotations()メソッドを使用してフィールドの注釈を読み取ることができます。

bannerAds