パラメータを受け取るアノテーションを作る。
「@Hoge("xxx")」といった感じで、パラメータを指定できるアノテーションを作ります。
作り方
- アノテーションを作ります。
- アノテーションにパラメータの値を返すメソッドを定義します。
- メソッド追加により、パラメータを指定できるようになります。
- メソッド名=パラメータ名、となります。
- 値のみをパラメータに指定した場合、value()メソッドの戻り値となります。
- パラメータの型はメソッドの戻り値で決まります。「プリミティブ、String、Class、列挙、注釈、およびそれらの型の配列」が使えます。(→http://java.sun.com/j2se/1.5.0/ja/docs/ja/guide/language/annotations.htmlより。)
以下はパラメータ指定をサポートしたアノテーションのサンプルです。
/** * 文字列をパラメータで指定できるアノテーション */ @Retention( RetentionPolicy.RUNTIME ) static @interface WithSimpleValue { String value(); } /** * 複数の値を指定できるアノテーション */ @Retention( RetentionPolicy.RUNTIME ) static @interface WithValue { String string(); String[] stringArray(); int integer(); boolean bool(); java.lang.Class<? extends InputStream> type(); Thread.State state(); }
パラメータを指定して、クラスにアノテーションを付加する。
こんな感じ。
- 「=」と「,」区切りで名前と値を指定します。
// WithSimpleValue, WithValueアノテーションが付いたクラス「Test」 @WithSimpleValue("simple") @WithValue( string = "aaa", stringArray = { "a", "b", "c" }, bool = false, integer = 1000, state = Thread.State.BLOCKED, type = ByteArrayInputStream.class ) static class Test {}
アノテーションから値を得る。
値の取得も簡単にできます。クラスからアノテーションを取ってきて、メソッドを呼ぶだけ。
// Testクラスから WithValue アノテーションを取得する。 WithSimpleValue v = Test.class.getAnnotation( WithSimpleValue.class ); // アノテーションの値を取得。 System.out.println( v.value() ); // Testクラスから WithValue アノテーションを取得する。 WithValue v2 = Test.class.getAnnotation( WithValue.class ); // アノテーションの値を取得。 System.out.println( v2.string() ); for ( String str : v2.stringArray() ) { System.out.println( str ); } System.out.println( v2.integer() ); System.out.println( v2.bool() ); System.out.println( v2.state() ); System.out.println( v2.type() );
実行結果です。
simple aaa a b c 1000 false BLOCKED class java.io.ByteArrayInputStream