系统内置的注解
@Override 重写父类方法
@Deprecated 表示方法已过时
自定义
格式
public @interface MyAnno{
int age() default 1;
String name();
}
其中,age name 在这里不是接口方法,而是指当前注解的属性
使用注解时
@MyAnno(age = 1,name = "张三")
public void setName(String name) {
this.name = name;
}
元注解
用于描述注解的注解
- @Target:描述注解能够作用的位置
- ElementType
- Type:可以作用于类上
- METHOD:可以作用于方法上
- Field:可以作用于成员变量上
- ElementType
- @Retention:描述注解保留的阶段
- RetentionPolicy
- RUNTIME:可以保留到class字节码文件中,并且能被JVM读取到
- RetentionPolicy
- @Documented:生成api文档时可以被抽取过去,默认是不会的
- @Inherited:表示当前上绑定的注解可以被子类继承
注解解析
@MyAnno(className = "demo1",methodName = "show")
public class Program {
public static void main(String[] args) {
// 获取字节码文件对象
Class<Program> programClass= Program.class;
MyAnno anno= programClass.getAnnotation(MyAnno.class);
String className= anno.className();
String methodName= anno.methodName();
System.out.println(className);
System.out.println(methodName);
}
}