------- android培训、java培训、期待与您交流! ----------
@Retention(RetentionPolicy.RUNTIME) //运行时有效 @Target({ElementType.METHOD,ElementType.TYPE}) //使用范围为方法和类,采用数组的方式设置属性 public @interface ItcastAnnotation { String color() default "blue"; String value();//每个注解都有Vlaue()属性 int[] arrayAttr() default {3,4,4}; EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED; MetaAnnotation annotationAttr() default @MetaAnnotation("lhm"); }
public @interface MetaAnnotation { String value(); }
@ItcastAnnotation(annotationAttr=@MetaAnnotation("flx"),color="red",value="abc",arrayAttr=1) //多个参数,需要分别指定参数值 public class AnnotationTest { @SuppressWarnings("deprecation") @ItcastAnnotation("xyz") //如果注解中有一个名称为value的属性,且你只想设置value属性 //(即其他属性都采用默认值或者你只有一个value属性),那么可以省略value=部分,例如:@MyAnnotation("lhm")。 public static void main(String[] args) throws Exception{ System.runFinalizersOnExit(true); //通过反射获取注解属性 if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){ ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class); System.out.println(annotation.color()); System.out.println(annotation.value()); System.out.println(annotation.arrayAttr().length); System.out.println(annotation.lamp().nextLamp().name()); System.out.println(annotation.annotationAttr().value()); } Method mainMethod = AnnotationTest.class.getMethod("main", String[].class); ItcastAnnotation annotation2 = (ItcastAnnotation)mainMethod.getAnnotation(ItcastAnnotation.class); System.out.println(annotation2.value()); } @Deprecated public static void sayHello(){ System.out.println("hi,传智播客"); } }
------- android培训、java培训、期待与您交流! ----------