javaでコメント内容を読み取る方法

Javaではリフレクションを使用してアノテーションの内容を読み取ることができます。

  1. リフレクションを使って、アノテーションを読み込む対象であるクラス、メソッド、フィールドなどのオブジェクトを取得する。
  2. アノテーションの取得
  3. annotationClass クラスの注釈を取得
  4. ネイティブの日本語で言い換えると?

クラスのコメントの内容を読み込む方法を示すサンプルコードを以下に示します。

import java.lang.annotation.Annotation;

public class Main {
    public static void main(String[] args) {
        Class<MyClass> clazz = MyClass.class;
        
        // 获取类的所有注释信息
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        
        // 获取特定注释信息
        MyAnnotation myAnnotation = clazz.getAnnotation(MyAnnotation.class);
        if (myAnnotation != null) {
            System.out.println(myAnnotation.value());
        }
    }
}

@MyAnnotation("这是一个注释")
class MyClass {
    
}

@interface MyAnnotation {
    String value();
}

上記コードを実行すると、以下の出力が得られます。

@MyAnnotation(value=这是一个注释)
这是一个注释
bannerAds