三种内定的Annotation
1,@Override 声明方法是重写的
2,@Deprecated 声明已过时的方法或类
3,@SuppressWarnings 压制警告信息,里面可以是数组类型,{deprecation,unchecked,fallthrough,path,serial,finnally,all}
自定义Annotation
@Documented //文档注释
@Inherited //继承的类也继承注解
@Target(value={ElementType.TYPE,ElementType.METHOD,ElementType.FIELD}) //设置注解作用的地方,type为类
@Retention(RetentionPolicy.RUNTIME) //指定在运行时也起作用
public @interface TestAnno {
public String value() default "aa";
public int key() default 1;
public my tt() default my.asd;
}
可以通过反射机制调用
Class<?> class1=Class.forName("com.bean.Student");
@SuppressWarnings("all")
Method method=class1.getMethod("say", null);
Annotation[] annotations=method.getAnnotations();
for (Annotation annotation : annotations) {
if(annotation instanceof TestAnno){
TestAnno ts=(TestAnno)annotation;
System.out.println(ts.key());
}
}