注解笔记

103 阅读1分钟

一、Java中常见注解

(1)JDK自带注解

@Override 覆盖了父类或接口的方法(重写)

@Deprecated 标记方法过时

@SuppressWarnings 标记忽略警告

(2)第三方注解

如Spring的:@Autowired @Service

二、注解分类

(1)按运行机制分为

1.1、源码注解 只在源码存在,编译成.class文件后不存在

1.2、编译时注解 在源码和.class文件都存在,如@Override、@Deprecated、@SuppressWarnings

1.3、运行时注解 在运行时还起作用,甚至影响运行逻辑(如:@Autowired)

(2)按来源分

1.1、JDK自带

1.2、第三方注解

1.3、自定义注解

三、自定义注解

//元注解(注解的注解)
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description{//使用@interface关键字定义注解
    String desc();//成员以无参无异常方式声明
    String author();//只有一个成员时必须以value命名
    int age() default 18;//可以用default指定默认值
}
//注解类可以没有成员,称为标识注解

(1)@Target

表示注解的作用域(当前注解可作用于方法、变量等)

(2)@Retention

表示注解的生命周期

SOURCE 只在源码显示

CLASS 编译时会记录到.class文件

RUNTIME 运行时存在,可通过反射获取

(3)@Inherited

允许子类注解继承(Inherited只能拿到父类的注解,拿不到父类方法以及接口的注解)

(4)@Documented

生成javadoc时会包含该注解

(5)使用自定义注解

@<注解名>(<成员名1>=<成员值1>,…) 如:

@Description(desc="我是描述",author="作者",age=8)

四、解析注解

//1、使用类加载器加载类
Class c = Class.forName("com.test.anTest");
//2、找到类上面的注解
boolean isExist = c.isAnnotationPresent(Description.class);//判断是否存在该注解
if(isExist){
    //拿到注解实例
    Description d = (Description)c.getAnnotation(Description.class);
    System.out.println(d.value());
}
//3、找到方法上的注解
Method[] ms = c.getMethods();
    for(Method m : ms){
        boolean isMExist = m.isAnnotationPresent(Description.class);
        if(isExist){
        Description d = (Description)m.getAnnotation(Description.class);
        System.out.println(d.value());
    }
}