java注解

2020-11-06  本文已影响0人  赵荣晖

一、jdk中常见注解

二、注解分类(按照运行机制分)

三、自定义注解

package com.tiandy.producer;
import java.lang.annotation.*;
//自定义注解
/*
   1、使用@interface 关键字定义注解
   2、成员以无参无异常方式声明
   3、可以用default为成员指定一个默认值
   4、成员类型是受限的,合法的类型包括原始类型及String、class、Annotation、Enumeration
   5、如果注解只有一个成员,则成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)
   6、注解类可以没有成员,没有成员的注解称为标识注解
 */
//元注解,即用在注解上的注解。
//注解的作用域: CONSTRUCTOR:构造方法声明;FIELD:字段声明;LOCAL_VARIABLE:局部变量声明;METHOD:方法声明;
// TYPE:类,接口;PARAMETER:参数声明;PACKAGE:包声明;
@Target({ElementType.METHOD, ElementType.TYPE})
//注解生命周期:SOURCE:只在源码中显示,编译时会放弃;CLASS:编译时会记录到class中,运行时忽略;RUNTIME:运行时存在,可以通过发射读取。
@Retention(RetentionPolicy.RUNTIME)
//允许子类继承
@Inherited
//生成javadoc会包含注解信息
@Documented
public @interface Description {
    String desc();
    String author();
    int age() default 18;
}

四、使用自定义注解

package com.tiandy.producer;
/*
注解使用方法
@<注解名>(<成员名1>="成员值1",成员名2>="成员值2",...)
*/
public class UseDescription {
    @Description(desc="I am abc",author="zrh",age=20)
    public String abc(){
        return "abc";
    }
}

五、解析注解

通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑。

public class TestDesc {

    public static void main(String[] args) {
        try {
            //使用类加载器加载类
            Class cla = Class.forName("com.tiandy.producer.UseDescription");
            //找到类上面的注解,参数为注解对应的class名称
            boolean flag = cla.isAnnotationPresent(Description.class);
            if(flag){
                Description d = (Description)cla.getAnnotation(Description.class);
                System.out.println("desc==="+d.desc());
                System.out.println("author===="+d.author());
            }
            //找到方法的注解
            Method[] ms = cla.getMethods();
            for (Method m :ms){
                boolean temp = m.isAnnotationPresent(Description.class);
                if (temp){
                    Description desc = (Description)m.getAnnotation(Description.class);
                    System.out.println("desc==="+desc.desc());
                    System.out.println("author===="+desc.author());
                }
            }
            //另一种解析方法
            for(Method m:ms){
                //拿到所有的注解
                Annotation[] annotations = m.getAnnotations();
                for (Annotation a:annotations){
                    if(a instanceof Description){
                        Description d = (Description) a;
                        System.out.println(d.desc());
                        System.out.println(d.author());
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读