はじめてのアノテーション作成
アノテーションを作ってみます。
作成
クラスやインターフェイスと同じように作成できます。「class」の代わりに「@interface」でアノテーションであることを宣言します。
構文:
<修飾詞> @interface <アノテーション名> { ... }
サンプル(Mike.java):
public @interface Mike {}
アノテーションのアノテーション
アノテーションの使われ方を示すためのアノテーションが、組み込みで用意されています。
Retention
アノテーション保持のポリシーを指定します。ポリシーは引数で指定し、利用可能な値はRetentionPolicyで定義されています。
- RUNTIME
- クラスファイルに記録され実行時に参照できる。
- CLASS
- クラスファイルに記録されるが実行時には保持されない。(何も指定しない場合これになります。)
- SOURCE
- コンパイル時に破棄される。
※詳細はRetentionPolicyのJavaDocを参照ください。
RUNTIMEのアノテーション:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention( RetentionPolicy.RUNTIME ) @interface Runtime {}
CLASSのアノテーション:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention( RetentionPolicy.CLASS) @interface Class {}
SOURCEのアノテーション:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention( RetentionPolicy.SOURCE ) @interface Source {}
メイン:
import java.lang.annotation.Annotation; public class List { // いろいろ付加 @Runtime @Class @Source class Annotated {} // メイン public static void main ( String[] args ) { // アノテーション一覧を表示 Annotation[] as = Annotated.class.getAnnotations(); for ( int i = 0; i < as.length; i++ ) { // Runtime以外は消えてなくなる。 System.out.println( as[i].toString() ); } } }
出力:
@annotation.Runtime()
Target
アノテーションが指定可能なプログラム要素(フィールド、コンストラクタ、引数..etc..)を指定します。
- 指定可能なプログラム要素はElementTypeで定義されています。これをアノテーションの引数で指定します。
- 作成したアノテーションを利用する際に、これで指定された要素以外に設定すると、コンパイルエラーとなります。
サンプル:
import java.lang.annotation.ElementType; import java.lang.annotation.Target; // アノテーションの指定可能な要素を宣言 // この場合、フィールドとメソッドの引数に指定できる。 @Target({ElementType.FIELD, ElementType.PARAMETER }) public @interface Mii {}
Inherited
このアノテーションが継承されるかどうかを宣言します。継承される場合、このアノテーションを親クラスに付加するとそれを派生した子クラスもアノテーションが付加されたと見なされます。
サンプル:
// 継承されるアノテーション @Inherited @Retention( RetentionPolicy.RUNTIME ) static @interface InheritedAnnotation {} // 継承されないアノテーション @Retention( RetentionPolicy.RUNTIME ) static @interface NormalAnnotation {} // 親要素にのみアノテーションを付加 @InheritedAnnotation @NormalAnnotation static class Parent {} static class Child extends Parent {} // メイン public static void main ( String[] args ) { // 子のアノテーション一覧を表示 Annotation[] as = Child.class.getAnnotations(); for ( int i = 0; i < as.length; i++ ) { // @Inherited付きアノテーションのみ取得できる。 System.out.println( as[i].toString() ); } }
出力:
@annotation.InheritedSample$InheritedAnnotation()