アノテーションは、クラス、フィールド、メソッド、パラメータなどのプログラム要素にメタデータ情報を追加できる、メタデータの説明を提供するためのメカニズムです。注釈はコンパイル時に処理でき、その情報は実行時に Java リフレクション メカニズムを通じて取得することもできます。
以下は、Java SE でのアノテーションの使用例です。
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String name();
int age() default 20;
String[] hobbies();
}
この例では、MyAnnotation は @Retention(RetentionPolicy.RUNTIME) および @Target(ElementType.METHOD) として定義される注釈で、実行時にまだ存在し、メソッドに作用することを示します。注釈には、名前、年齢、趣味という 3 つの要素が含まれており、このうち、年齢要素のデフォルト値は 20 です。
メソッドで MyAnnotation を使用する方法の例を次に示します。
public class MyClass {
@MyAnnotation(name = "John Smith", hobbies = {
"reading", "writing"})
public void myMethod() {
// 方法体
}
}
この例では、myMethod メソッドに MyAnnotation を追加し、それに name 要素と Hobby 要素の値を追加しました。上記の定義によれば、age 要素はデフォルト値 20 を使用します。
リフレクション メカニズムを使用して、MyAnnotation アノテーションの要素値を取得できます。次に例を示します。
public class AnnotationDemo {
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Method method = obj.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("name: " + annotation.name());
System.out.println("age: " + annotation.age());
System.out.println("hobbies: ");
for (String hobby : annotation.hobbies()) {
System.out.println(hobby);
}
}
}
この例では、リフレクション メカニズムを通じて myMethod メソッドの MyAnnotation アノテーションを取得し、すべての要素の値を出力します。
上記のコードを実行すると、次の出力が得られます。
name: John Smith
age: 20
hobbies:
reading
writing