Java8注解新增两个主要特性,一个类型注解,目前没看到什么用,留着再研究吧(坏习惯!),另一个就是我要说的这个新特性Repeatable感觉棒棒的,可以一次传好多值啦。来看我的这个 Demo
###code
public class RepeatableAnnotationDemo { public static void main(String[] args) { testRepeatable(); } @myAnno(str = "hs", size = 2) @myAnno(str = "Ys", size = 1) @myAnno(str = "zs", size = 3) public static void testRepeatable() { try { Class clazz = Class.forName("Book.RepeatableAnnotationDemo"); Method method = clazz.getMethod("testRepeatable"); RepeatableAnno annotation = method.getAnnotation(RepeatableAnno.class); System.out.println(annotation); myAnno[] annos1 = annotation.value(); for (myAnno anno : annos1) { System.out.println(anno + "->size:" + anno.size() + " str:" + anno.str()); } System.out.println("------------------------------------------------"); myAnno[] annos = method.getAnnotationsByType(myAnno.class); for (myAnno anno : annos) { System.out.println(anno + "->size:" + anno.size() + " str:" + anno.str()); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } }}@Retention(RetentionPolicy.RUNTIME)@Repeatable(RepeatableAnno.class)@interface myAnno { String str() default " "; int size() default 0;}@Retention(RetentionPolicy.RUNTIME)@interface RepeatableAnno { myAnno[] value();}
@Book.RepeatableAnno(value=[@Book.myAnno(size=2, str=hs), @Book.myAnno(size=1, str=Ys), @Book.myAnno(size=3, str=zs)])@Book.myAnno(size=2, str=hs)->size:2 str:hs@Book.myAnno(size=1, str=Ys)->size:1 str:Ys@Book.myAnno(size=3, str=zs)->size:3 str:zs------------------------------------------------@Book.myAnno(size=2, str=hs)->size:2 str:hs@Book.myAnno(size=1, str=Ys)->size:1 str:Ys@Book.myAnno(size=3, str=zs)->size:3 str:zs