LoginSignup
1
7

More than 5 years have passed since last update.

独自マーカーアノテーションを活用する

Last updated at Posted at 2018-05-02

目的

  • 独自のマーカー用アノテーションを作成する。
  • class・interface・methodに付与されたアノテーションの有無により条件を加える。

利用方法

1. 独自マーカーアノテーションを作成する

参考記事:ちょっと特殊なJavaのアノテーション

アノテーションの対象を指定する:Target

  • class・interface と method を対象とする。
    java.lang.annotation.ElementType より TYPE、METHOD を選択する。
  • ElementType を複数選択する場合は、弧{}を使用しカンマ,で区切る。
SampleAnnotation.java
/**
 * class・interfaceとmethodに付与可能とするアノテーション
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@interface SampleAnnotation {

}

アノテーションの読み込みタイミングを指定する:Retention

SampleAnnotation.java
/**
 * 実行時のVMの読み込みを表すアノテーション
 */
@Retention(RetentionPolicy.RUNTIME)
@interface SampleAnnotation {

}

2. アノテーション付与の有無による条件を加える

利用するマーカーアノテーション (1.で作成したアノテーション)

【利用例】
本アノテーション@IgnoreSessionが付与されたclass・interfaceまたはmethodは、
セッションを扱う処理ではない ことを表すマーカー用のアノテーションとする。

IgnoreSession.java
/**
 * セッションを扱わない処理であることを表すアノテーション
 * セッションを扱わない処理に付与
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreSession {

}

判定処理

本アノテーション@IgnoreSessionが付与されたかの有無を判定する処理を記述する。

class・interfaceの検証

bean : class・interfaceの実体を表す

  1. 通常の場合

    class・interfaceを検証する
    
    // class・interfaceに対する検証
    if (targetClass.isAnnotationPresent(IgnoreSession.class)
    
        // セッションを扱わないclass・interfaceである場合の処理
    }
    
  2. spring等のfw使用の場合
    springAOPの処理において、検証対象なるbeanの実体がProxyクラスとなる場合があるため、
    ②「class・interfaceに対する検証」の前に①「beanに対してProxyクラスであるかを検証」する処理が必要となる。

    参考記事:SpringAOPが適用されたbeanを使ったメタプログラミングでハマった件

    class・interfaceを検証する
    
    // ①beanに対してProxyクラスであるかを検証
    Class<?> targetClass = null;
    if (AopUtils.isAopProxy(bean)) {
        targetClass = AopUtils.getTargetClass(bean);
    } else {
        targetClass = bean.getClass();
    }
    
    // ②class・interfaceに対する検証
    if (targetClass.isAnnotationPresent(IgnoreSession.class)
    
        // セッションを扱わないclass・interfaceである場合の処理
    }
    

methodの検証

method : methodの実体を表す

methodを検証する

// methodに対する検証
if (method.isAnnotationPresent(IgnoreSession.class)) {

    // セッションを扱わないmethodである場合の処理
}

参考まとめ

1
7
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
1
7