Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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メソッドだけ呼ばれてますね。

参考サイト

hogelog
hogelog http://hogel.org/
http://hogel.org/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした