LoginSignup
23
24

More than 5 years have passed since last update.

アノテーションを自作してみる。

Posted at

カスタムクラスローダを作ってみるに引き続き、リフレクションとかで遊ぶ。アノテーションでなんかしてみる。

MyAnnotation.java

import java.lang.reflect.Method;
import java.lang.annotation.Annotation;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class MyAnnotation {
    public static void main(String[] args) {
        Class clazz = MyAnnotation.class;
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            try {
                Annotation[] annotations = method.getDeclaredAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation.annotationType().equals(CallMe.class)) {
                        method.invoke(null); 
                    }
                }
            } catch (Exception e) { // nice catch!
            }
        }
    }

    @CallMe
    static void test1() {
        System.out.println("call test1");
    }

    static void test2() {
        System.out.println("call test2");
    }

    @CallMe
    static void test3() {
        System.out.println("call test3");
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface CallMe {
}

Classオブジェクトから@CallMeアノテーションのついているstaticメソッドだけ呼び出し。

実行結果

$ java MyAnnotation 
call test1
call test3

@CallMeをつけたメソッドtest1, test3メソッドだけ呼ばれてますね。

参考サイト

23
24
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
23
24