gpt4 book ai didi

java - 自动包装@Repeatable 注解的顺序

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:42 25 4
gpt4 key购买 nike

以前,我习惯于手工声明一个wrapper annotation,用一个数组,然后这样调用它:

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

因为我是用 { ... } 初始值设定项创建一个数组,当我稍后通过反射访问此方法时,很明显顺序与声明的顺序相同。

但是,当我使用 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() {}

一切似乎都完美无缺(当通过反射访问时),但我不想依赖未记录的东西。在我看来很明显应该是这种情况,但我无法在任何地方找到它!任何人都可以阐明这一点吗?

最佳答案

这是 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.

(强调我的)

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

关于java - 自动包装@Repeatable 注解的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com