Javaでアノテーションの値を取得する方法

Java では、アノテーションの値を取得するために、リフレクションメカニズムを使用できます。以下は、アノテーションの値を取得する方法を示す例です。

// 定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation {

String value(); } // 使用注解 @MyAnnotation(“Hello”) class MyClass {

 

} public class Main {

 

public static void main(String[] args) {

 

// 获取注解的值

 

MyAnnotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);

 

if (annotation != null) {

 

String value = annotation.value();

 

System.out.println(value);  // 输出:Hello

 

}

 

} }


まずMyAnnotationアノテーションを作成し、valueという属性を定義します。そしてMyClassクラスをMyAnnotationアノテーションで装飾し、アノテーションのvalueにHelloと指定します。Mainクラスで、MyClass.class.getAnnotation(MyAnnotation.class)メソッドを使ってMyClassクラス上のMyAnnotationアノテーションの値を取得し、annotation.value()メソッドでアノテーションの値を取得して、それをもとに処理を行います。

bannerAds