在注解类中增长String color(); @MyAnnotation(color="red")
MyAnnotation a = (MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class); System.out.println(a.color()); 能够认为上面这个@MyAnnotation是MyAnnotaion类的一个实例对象
String color() default "yellow";
String value() default "zxx"; 若是注解中有一个名称为value的属性,且你只想设置value属性(即其余属性都采用默认值或者你只有一个value属性),那么能够省略value=部分,例如:@MyAnnotation("lhm")。
int [] arrayAttr() default {1,2,3}; @MyAnnotation(arrayAttr={2,3,4}) 若是数组属性中只有一个元素,这时候属性值部分能够省略大括
EnumTest.TrafficLamp lamp() ; @MyAnnotation(lamp=EnumTest.TrafficLamp.GREEN)
MetaAnnotation annotationAttr() default @MetaAnnotation("xxxx"); @MyAnnotation(annotationAttr=@MetaAnnotation(“yyy”) ) 能够认为上面这个@MyAnnotation是MyAnnotaion类的一个实例对象,一样的道理,能够认为上面这个@MetaAnnotation是MetaAnnotation类的一个实例对象,调用代码以下: MetaAnnotation ma = myAnnotation.annotationAttr(); System.out.println(ma.value());
package staticimport.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import staticimport.enums.TrafficEnumTest; @Retention(RetentionPolicy.RUNTIME)//元注解 @Target({ElementType.TYPE,ElementType.METHOD}) public @interface LH { //字符串类型,带默认值 String color() default "red"; //字符串类型 String value(); //整型数组类型,带默认值 int[] arrayAttr() default {1,2,3}; //枚举类型,带默认值 TrafficEnumTest.TrafficLampEnum lamp() default TrafficEnumTest.TrafficLampEnum.YELLOW; //注解类型,带默认值 MetaAnnotation annotation() default @MetaAnnotation("xyz"); //Class类型,带默认值 Class<?> clazzAttr() default String.class; }
package staticimport.annotation; //只有一个value属性值须要赋值,能够省略value= //数组属性值只有一个,能够省略{} @LH(color = "yellow", value = "abc", arrayAttr = 5, annotation = @MetaAnnotation("xxx"), clazzAttr = AnnotationTest.class) @SuppressWarnings("deprecation") public class AnnotationTest { public static void main(String[] args) { System.runFinalizersOnExit(true); AnnotationTest.sayHello(); if (AnnotationTest.class.isAnnotationPresent(LH.class)) { LH lh = (LH) AnnotationTest.class.getAnnotation(LH.class); System.out.println(lh); System.out.println(lh.color()); System.out.println(lh.value()); System.out.println(lh.arrayAttr().length); System.out.println(lh.lamp().nextLamp()); System.out.println(lh.annotation().value()); System.out.println(lh.clazzAttr()); } } // 标注本方法已过期,提示用户不要再使用!但不影响已经使用的! @Deprecated @LH("kkk") public static void sayHello() { System.out.println("Hello,LH!"); } }
package staticimport.annotation; public @interface MetaAnnotation { String value(); }
注:java
注解属性类型能够是8大基本数据类型、String、Class及其调用类型、枚举、注解、基本数据类型数组数组