Multiple annotations of the same type on one element?

前端 未结 8 1328
再見小時候
再見小時候 2020-11-30 21:39

I\'m attempting to slap two or more annotations of the same type on a single element, in this case, a method. Here\'s the approximate code that I\'m working with:

         


        
8条回答
  •  甜味超标
    2020-11-30 22:23

    Apart from the other ways mentioned, there is one more less verbose way in Java8:

    @Target(ElementType.TYPE)
    @Repeatable(FooContainer.class)
    @Retention(RetentionPolicy.RUNTIME)
    @interface Foo {
        String value();
    
    }
    
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @interface FooContainer {
            Foo[] value();
            }
    
    @Foo("1") @Foo("2") @Foo("3")
    class Example{
    
    }
    

    Example by default gets, FooContainer as an Annotation

        Arrays.stream(Example.class.getDeclaredAnnotations()).forEach(System.out::println);
        System.out.println(Example.class.getAnnotation(FooContainer.class));
    

    Both the above print:

    @com.FooContainer(value=[@com.Foo(value=1), @com.Foo(value=2), @com.Foo(value=3)])

    @com.FooContainer(value=[@com.Foo(value=1), @com.Foo(value=2), @com.Foo(value=3)])

提交回复
热议问题