Order auto wrapped annotations @Repeatable

I used to use a wrapper annotation declaration manually, with an array, and then called it like this:

@Foos({ @Foo(0), @Foo(1), @Foo(2) }) public void bar() {} 

Since I was creating an array with initializers { ... } , it was more than clear that the order should be the same in the declaration when I accessed this method later through Reflection.

However, when I use the new @Repeatable annotation from Java 8, can I guarantee that the order will be saved?

I declared a simple set of annotations:

 public @interface Foos { Foo[] value(); } @Repeatable(Foos.class) public @interface Foo { int value(); } 

and do some tests with a wide variety of scenarios:

 @Foo(0) @Foo(1) @Foo(2) public void bar1() {} @Foo(2) @Deprecated @Foo(5) @Foo(10) public void bar2() {} 

and everything works flawlessly (when accessed via Reflection), but I would not want to rely on undocumented materials. It seems obvious to me that it should be so, but I can’t find it anywhere! Can anyone shed some light on this?

+6
source share
1 answer

This section of the Java Language Specification says:

If the declaration context or context type has multiple annotations of the repeatable annotation type T, then it looks as if the context does not have explicitly declared annotations of type T and implicitly declared annotations containing the type of annotation T.

An implicitly declared annotation is called a container annotation, and multiple type T annotations that appear in the context are called basic annotations. The elements of the element (array) of the container annotation element are basic annotations in the order from left to right in which they appeared in context .

(my emphasis)

So, yes, the order of annotations in the container annotation is the same as the order of declaring repeated annotations.

+9
source

Source: https://habr.com/ru/post/975970/


All Articles