1.定义
@Target({ ElementType.METHOD, ElementType.PARAMETER }) // 只能写在方法或者参数上 public @interface Anno06 { }
2. 使用
public class test01 { @Anno01 //注解写在方法之上,若写在类外便会报错 public void test() { } }
①CLASS:编译器将把注解记录在类文件中,但在运行时 JVM 不需要保留注释。
②RUNTIME:编译器将把注解记录在类文件中,在运行时JVM 将保留注解,因此可以反射性地读取。
③SOURCE:编译器要丢弃的注解。
1. 定义
@Retention(RetentionPolicy.SOURCE) //只在源码中
@Retention(RetentionPolicy.RUNTIME) //使用该注解保留到运行前
public @interface Anno01 {
}
2.反射测试
public class test03 { public static void main(String[] args) throws NoSuchMethodException, SecurityException { Class clazz=test02.class; Method m=clazz.getDeclaredMethod("test"); System.out.println(m.isAnnotationPresent(Anno01.class)); } }
1. 定义
@Documented public @interface Anno10 { public String doc(); }
2. 使用
public class Test20 { @Anno10(doc = "我是文档注解") public void test() { } }
//然后选中项目,点击Project,选中Generate Javadoc,然后连续点两个next,输入框输入-encoding UTF-8 -charset UTF-8,最后finish生成javadoc文档,将index.html拖入浏览器查看即可
1.定义注解
@Retention(RetentionPolicy.RUNTIME) //定义注解1 public @interface Anno01 { }
@Inherited //定义注解2
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno02 {
}
2. 定义父类A和B
@Anno01 @Anno02 public class A { //定义父类A }
public class B extends A { //定义父类B继承父类A
}
3. 反射查看继承
public class Test { public static void main(String[] args) { Class clazz=B.class; Annotation[] as=clazz.getAnnotations(); //只输出了@cn.edu.xcu.annotation.v2.Anno02(),说明加上@Inherited才会被继承 for (Annotation annotation : as) { System.out.println(annotation); } } }
原文:https://www.cnblogs.com/yuanshuai1026/p/11564170.html