简体   繁体   中英

Order of automatically wrapped @Repeatable annotations

Before, I used to declare a wrapper annotation by hand, with an array, and then call it like so:

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

Since I was making an array with the { ... } initializers, it was more than clear that the order was to be the same of the declaration when I accessed this method later via Reflection.

However, when I use the new @Repeatable annotation from Java 8, do I have guarantee that the order will be kept?

I declared a simple set of annotations:

public @interface Foos {
  Foo[] value();
}

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

and run some tests with the most diverse scenarios:

@Foo(0) @Foo(1) @Foo(2)
public void bar1() {}

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

and everything seems to work flawlessly (when accessing via Reflection), but I would not like to rely on undocumented stuff. It seems obvious to me that that should be the case, but I can't find it anywhere! Can anyone shed a light on this?

Here's what the Java Language Specification says:

If a declaration context or type context has multiple annotations of a repeatable annotation type T, then it is as if the context has no explicitly declared annotations of type T and one implicitly declared annotation of the containing annotation type of T.

The implicitly declared annotation is called the container annotation, and the multiple annotations of type T which appeared in the context are called the base annotations. The elements of the (array-typed) value element of the container annotation are all the base annotations in the left-to-right order in which they appeared in the context .

(emphasis mine)

So yes, the order of the annotations in the container annotation is the same as the order of declaration of the repeatable annotations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM