使用反射和註解得到一個類的註解信息

package com.iotek.annotation;

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

public class AnnotationDemo {
    public static void main(String[] args) throws Exception {
        Class<?> classType = Class.forName("com.iotek.annotation.AnnotationTest");
        boolean flag1 = classType.isAnnotationPresent(Description.class);// 把註解當初是一個類
        if (flag1) {
            Description description = classType.getAnnotation(Description.class);
            System.out.println("類註解的描述:" + description.content());

        }
        Method[] methods = classType.getDeclaredMethods();
        for (Method method : methods) {
            if (classType.isAnnotationPresent(Author.class)) {
                Author author = (Author)method.getAnnotation(Author.class);
                System.out.println("方法註解的描述:" + author.name() + author.age());
            }
        }

    }

}

@Retention(RetentionPolicy.RUNTIME) // 這個註解信息會一直保留,直到Java虛擬機退出爲止
@Target(ElementType.METHOD) // 這個註解是作用在方法上面
@Documented
@interface Author { // 標記註解
    String name();

    int age();

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) // 作用在類上
@Documented
@interface Description {
    String content(); // 如果content是value,content就可以省略
}

@Description(content = "這是一個用來測試的類")
class AnnotationTest {
    @Author(name = "張三", age = 25)
    public void test() {
        System.out.println("test over");
    }
}
發佈了55 篇原創文章 · 獲贊 71 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章