认识JAVA自定义注解

目录

一、定义自定义注解

 二、注解类

三、解析自定义注解


一、定义自定义注解

//作用域
//构造方法声明CONSTRUCTOR、字段声明FIELD、局部变量声明LOCAL_VARIABLE
//方法声明METHOD、包声明PACKAGE、参数声明PARAMETER、类/接口TYPE
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
//生命周期
//只在源码显示,编译时没有 SOURCE;
//编译时记录到class中,运行时忽略 CLASS;
//运行时存在,可以通过反射读取 RUNTIME
@Retention(RetentionPolicy.RUNTIME)
//允许子类继承(接口不行),父类替换子类注解
@Inherited
//生成javadoc时会包含注解
@Documented
public @interface Description {   //@interface定义注解

    //double、float、byte、short、int、long、boolean 八种原始类型
    //成员类型除八种原始类型外,还包括String,Class,Annotation,Enumeration;
    //如果注解只有一个成员,则成员必须取名为value();使用注解时,可以忽略成员名和等号
    //注解可以没有成员,没有成员称为标识注解
    String value();  //成员以无参无异常方式声明

    String key() default "";  //可以指定default为成员默认值

}

 二、注解类


@Test("hello type")
public class Child {

    @Test("Hello method")
    public void sing() {

    }
}

三、解析自定义注解

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class ParseAnn {

    public static void main(String[] args) {
        try {
            //1.使用类加载器
            Class child = Class.forName("Child");
            //2.找到类上面的注解
            boolean isExist = child.isAnnotationPresent(Test.class);
            if (isExist) {
                //3.拿到注解实例
                Test test = (Test) child.getAnnotation(Test.class);
                System.out.println(test.value());
            }
            //4.找到方法上的注解
            Method[] methods = child.getMethods();
            for (Method method : methods) {
                /**
                 * 方式一
                 */
                boolean isMExist = method.isAnnotationPresent(Test.class);
                if (isMExist) {
                    Test methodAnnotation = method.getAnnotation(Test.class);
                    System.out.println(methodAnnotation.value());
                }
                /**
                 * 方式二
                 */
                Annotation[] annotations = method.getAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation instanceof Test) {
                        System.out.println(((Test) annotation).value());
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章