1.理解注解:给方法、类、变量等添加一个标签,对添加了标签的实体根据标签的内容进行一些操作。注解的本质是一个Annotation的接口
/**Annotation接口源码*/
public interface Annotation {
boolean equals(Object obj);
int hashCode();
Class<? extends Annotation> annotationType();
}
2.JDK提供的注解:
@Override: 标识当前是一个重写的方法,在编译时会校验
@Deprecated:标识当前是一个过时的方法
@SuppressWarnings:去除程序中的警告
3.元注解:注解的注解
@Retention:标明注解的存在时期
RetentionPolicy.SOURCE:存在于源码中
RetentionPolicy.CLASS:默认注解,存在于class字节文件中,但运行时拿不到
RetentionPolicy.RUNTIME:存在于程序运行时,自定义注解一般用该注解
@Target:标明该注解的作用范围,可以是类、接口、方法等
@Inherited - 标记这个注解是继承于哪个注解类
4.自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolice.RUNTIME)
@Inherited
@Documented
public @interface Rest{
String rule();
String user() default "admin";
}
5.解析注解
类注解(方法注解类似)
try{
Class c = Class.forName("com.enn.test.Device")
boolean isExist = c.inAnnotationPresent(Rest.class) //判断c是否有Rest注解
if(isExist){
Rest d = (Rest)c.getAnnotation(Rest.class) //获取到c类上的Rest注解实例
System.out.println(d.value()) //输出注解内容
}catch(ClassNotFoundException e){
e.printStackTrace();
}