java – 自动包装的@Repeatable注释的顺序

前端之家收集整理的这篇文章主要介绍了java – 自动包装的@Repeatable注释的顺序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在此之前,我曾经手工使用数组声明包装器注释,然后像这样调用它:
@Foos({ @Foo(0),@Foo(1),@Foo(2) })
public void bar() {}

由于我使用{…}初始化程序创建了一个数组,所以当我稍后通过Reflection访问此方法时,顺序与声明的相同是非常清楚的.

但是,当我使用Java 8中的新@Repeatable注释时,我是否保证将保留订单?

我宣布了一组简单的注释:

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

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

并针对最多样化的场景运行一些测试:

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

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

一切似乎完美无缺(当通过Reflection访问时),但我不想依赖于未记录的东西.我觉得应该是这样,但我无法在任何地方找到它!任何人都可以对此有所了解吗?

解决方法

这是 Java Language Specification所说的:

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.

(强调我的)

所以,是的,容器注释中的注释顺序与可重复注释的声明顺序相同.

原文链接:https://www.f2er.com/java/121554.html

猜你在找的Java相关文章