java 注解示例(@Retention)
作用:限制注解的保存范围(默认class),如果需要读取注解中的值,需要将retention设置为runtime
***************************
示例
@Retention(RetentionPolicy.RUNTIME)
@interface A{
String value() default "瓜田李下";
}
@A
class A1{
}
public class MyTest {
public static void main(String[] args) throws Exception{
Class<?> c=Class.forName("hello3.A1");
Annotation[] annotations=c.getAnnotations();
System.out.println(Arrays.toString(annotations));
if (annotations.length!=0){
for (Annotation annotation:annotations){
if (annotation instanceof A){
A a=(A)annotation;
System.out.println("注解在类A1上的value为:"+a.value());
}
}
}
if (c.isAnnotationPresent(A.class)){
A a=c.getAnnotation(A.class);
System.out.println("注解在类A1上的value值为:"+a.value());
}
}
}
******************
控制台输出
[@hello3.A(value="瓜田李下")]
注解在类A1上的value为:瓜田李下
注解在类A1上的value值为:瓜田李下
说明:如果不加注解@Retention(RetentionPolicy.Runtime),以上信息不会输出