Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
24
Help us understand the problem. What is going on with this article?
@hogelog

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

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

参考サイト

24
Help us understand the problem. What is going on with this article?
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
hogelog
hogelog http://hogel.org/

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
24
Help us understand the problem. What is going on with this article?