3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】アノテーション

Last updated at Posted at 2019-05-25

アノテーションの定義

  • @interface を付けるとアノテーションとしての定義となる。

アノテーションのパラメタ定義

  • アノテーションを使用する際のパラメタの宣言
TestAnnotation.java
public @interface TestAnnotation {
    String param1();
    String param2() default "defaultValue";
}
UserAnnotation.java
@TestAnnotation (param1="30", param2="100")
public UserAnnotation() {}

アノテーションの参照

  • リフレクションを使用して参照する。
参照クラス
    Class<?> c = UserAnnotation.class;
    for (Annotation a : c.getDeclaredAnnotations()) {
        System.out.println(a);
    }
コンソール出力
@com.example.demo.com.annotation.TestAnnotation(param2=100, param1=30)

メタアノテーション

TestAnnotation
@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation{}
  • アノテーションに対して付けられるアノテーションのこと。
  • そのうち、java側で用意されているのを標準メタアノテーションという。

    ex. Documented, Target, Retention, Ingerited

@Documented

  • Javadoc中にアノテーションの説明を記載するかどうか。

@Target

  • アノテーションの配置する場所を定義する。
種類 説明
TYPE クラス・インタフェース・enum・アノテーション
FIELD フィールド
METHOD メソッド
ANNOTATION_TYPE アノテーション型の宣言

@Retantion

  • アノテーションの情報がどの段階まで使用されるか。
種類 説明
SOURCE ソース上のみ保持、クラスファイル作成時に削除される。
CLASS クラスファイルでも保持できるがアプリケーション実行時には参照できない。
RUNTIME アプリケーション実行時でも使用可能。
リフレクションでアノテーションを参照するならこれが必要。

@Inherited

  • クラスを宣言したサブクラスにもアノテーションの情報を付与する。

参考サイト

@Documentedの挙動
https://qiita.com/opengl-8080/items/1cc996d9e8bb5c811567

@メタアノテーションとは
https://www.techscore.com/tech/Java/JavaSE/JavaLanguage/7-3/

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?