注解根据是否有成员变量可分为两类:标签注解和元注解
1.标签注解
常用的基本Annotation:
@Override
限定重写父类标签,在对复杂父类重写时能进行限制提示;
@Deprecated
表示已过时,不可再调用否则将出错
@SuppressWarnings
抑制编译器警告
@SafeVararag
抑制堆污染警告,例如不同类型数据存入集合中产生的堆污染
@FunctionanlInterface
限定函数式接口,接口中只能有一个抽象方法,支持lambda表达式
2.元注解
JDK提供的常用的几个元注解
@Retention:用于指定修饰的Annotation可以保留多长时间
//这个自定义的注解可以保留到运行时
@Retention(RetentionPolicy.RUNTIME)
public @interface Testable{}
//这个注解将被编译器直接丢弃
@Retention(RetentionPolicy.SOURCE)
public @interface Testable{}
@Target:限定注解只能修饰哪些程序单元
//此注解只能修饰成员变量
@Target(ElementType.FIELD)
public @interface Testable{}
//此注解只能修饰方法
@Target(ElementType.METHOD)
public @interface Testable{}
@Interned:使用此注解修饰的类,其之类将默认继承这个元注解
@Interned
public @interface Testable{}
//父类用@Interned修饰
@Interned
class Base{}
//则继承他的子类默认继承了@Interned注解
Public class test extends Base{}
3.自定义注解
自定义注解和定义接口类似
//只是在接口前加上@符号饥渴
public @interface test{}
可以在自定义注解中添加成员函数,就是元注解
反之则是标签注解
//得到Test类下的info方法中的所有注解
Annotation[] annotations = Class.forName("Test").getMethod("info", String[].class).getAnnotations();
//遍历annotations中所有的注解
for (Annotation a:
annotations) {
System.out.println(a);
}