Multiple annotations of the same type on one element?

前端 未结 8 1234
再見小時候
再見小時候 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:16

    If you have only 1 parameter "bar" you can name it as "value". In this case you wont have to write the parameter name at all when you use it like this:

    @Foos({@Foo("one"), @Foo("two")})
    public void haha() {}
    

    a bit shorter and neater, imho..

    0 讨论(0)
  • 2020-11-30 22:22

    combining the other answers into the simplest form ... an annotation with a simple list of values ...

    @Foos({"one","two"})
    private String awk;
    
    //...
    
    public @interface Foos{
        String[] value();
    }
    
    0 讨论(0)
  • 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)])

    0 讨论(0)
  • 2020-11-30 22:30

    Repeating annotations in Java 8

    In Java 8 (released in March 2014), it is possible to write repeated/duplicate annotations.

    See tutorial, Repeating Annotations.

    See specification, JEP 120: Repeating Annotations.

    0 讨论(0)
  • 2020-11-30 22:32

    http://docs.oracle.com/javase/tutorial/java/annotations/repeating.html

    Starting from Java8 you can describe repeatable annotations:

    @Repeatable(FooValues.class)
    public @interface Foo {
        String bar();
    }
    
    public @interface FooValues {
        Foo[] value();
    }
    

    Note, value is required field for values list.

    Now you can use annotations repeating them instead of filling the array:

    @Foo(bar="one")
    @Foo(bar="two")
    public void haha() {}
    
    0 讨论(0)
  • 2020-11-30 22:39

    In the current version of Java, I was able to resolve this issue with the following annotation:

    @Foo({"one", "two"})
    
    0 讨论(0)
提交回复
热议问题