1 Java定义的基本注解
@Overide 检查父类中有无被修饰的方法。
@Deprecated 标记为已过时。
@SuppressWarnings 抑制编译警告
@SafeVarargs
堆污染:将一个不带泛型的对象赋给了一个带泛型的变量,往往会出现堆污染。会出现警告,该注解抑制该警告
@FunctionalInterface 用来指定某个接口必须是函数式接口。
2 自定义注解
//使用如下注解后,定义的注解才会在JVm运行时装载.class时读取修饰的注解信息
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name() default "dema";
int age() default 1;
注意:一定要添加@Retention(RetentionPolicy.RUNTIME)。
添加到一个方法中:
public class TextAnnotation {
@MyAnnotation(name="dema",age=10)
public void getInfo(){
System.out.println("run in getInfo");
}
}
测试:获取注解上的值信息。
public static void text02() throws NoSuchMethodException,
SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = Class
.forName("com.text.annotation.TextAnnotation");
Method method = clazz.getMethod("getInfo");
Annotation[] annArray = method.getAnnotations();//获取该方法上的注解信息
for (Annotation annotation : annArray) {
if(annotation instanceof MyAnnotation){
//获取该注解成员值
System.out.println(((MyAnnotation)annotation).name()+" "+((MyAnnotation)annotation).age());
}
}
}
结果: