以下の内容はhttps://unageanu.hatenablog.com/entry/20071025/1193304757より取得しました。


パラメータを受け取るアノテーションを作る。

「@Hoge("xxx")」といった感じで、パラメータを指定できるアノテーションを作ります。

作り方

  1. アノテーションを作ります。
  2. アノテーションにパラメータの値を返すメソッドを定義します。

以下はパラメータ指定をサポートしたアノテーションのサンプルです。

/**
 * 文字列をパラメータで指定できるアノテーション
 */
@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



以上の内容はhttps://unageanu.hatenablog.com/entry/20071025/1193304757より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14