加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:43:56 所属栏目:Java 来源:网络整理
导读:在此之前,我曾经手工使用数组声明包装器注释,然后像这样调用它: @Foos({ @Foo(0),@Foo(1),@Foo(2) })public void bar() {} 由于我使用{…}初始化程序创建了一个数组,所以当我稍后通过Reflection访问此方法时,顺序与声明的相同是非常清楚的. 但是,当我使用Ja
在此之前,我曾经手工使用数组声明包装器注释,然后像这样调用它:
@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.

(强调我的)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读