在维护对 Java 7 的支持的同时使用 @Repeatable
Java 8 通过使用容器"注释支持可重复注释:
Java 8 came with support for repeatable annotations through the use of "container" annotations:
@Repeatable(FooContainer.class)
@interface Foo {
String value();
}
@interface FooContainer {
Foo[] value();
}
@Foo("bar")
@Foo("baz")
public class SomeClass { }
我有一个要支持 Java 7(或更新版本)的库.该库广泛使用了注释,并且可以从支持可重复注释中受益匪浅.
I have a library where I want to support Java 7 (or newer). This library makes extensive use of annotations, and would greatly benefit from supporting repeatable annotations.
据我所知,即使在 Java 7 中,容器注释也能工作,只有一个人必须使用它:
From what I understand, the container annotation works even in Java 7, only one would have to use this instead:
@FooContainer({@Foo("bar"),@Foo("baz")})
public class SomeClass { }
我最终想要的是:如果我的库的用户使用的是 Java 8,那么用户将能够使用重复的注释.如果用户使用的是 Java 7,则必须坚持手动编写容器注解.
What I would ultimately like is: If the user of my library is using Java 8 the user will be able to use repeated annotation. If the user is using Java 7, he must stick to manually writing the container annotation.
这样的事情有可能吗?
您需要提供两个版本的库:
You need to provide two versions of your library:
- 一个打算与 Java 8 一起使用的,它对定义进行元注释
Foo
和@Repeatable
. - 一种用于 Java 7,它明确定义了
Foo
和FooContainer
.
- one intended for use with Java 8, which meta-annotates the definition
of
Foo
with@Repeatable
. - one intended for use with Java 7, which explicitly defines both
Foo
andFooContainer
.
不幸的是,您不能同时支持 Java 7 和一个版本的库的重复注释.如果您希望客户端能够重复注释,则必须将 Foo
元注释为 @Repeatable
.java.lang.annotation.Repeatable
仅在 Java 8 中定义.因此,如果注释 Foo
元注释为 @Repeatable
,则 Foo
code>Foo 和 SomeClass
只能在 JDK 8 及以上版本上编译运行.(它只能在 JDK 8 上运行,因为当加载 SomeClass 时,将加载 Foo,并且将加载 Foo 上的任何元注释.)
Unfortunately, you can't support both Java 7 and repeating annotations with one version of your library. If you want clients to be able to repeat the annotation, then Foo
must be meta-annotated as @Repeatable
. java.lang.annotation.Repeatable
is defined only in Java 8. Therefore, if annotation Foo
is meta-annotated as @Repeatable
, both Foo
and SomeClass
can only be compiled and run on JDK 8 and above. (It can only be run on JDK 8 because when SomeClass is loaded, then Foo will be loaded, and any meta-annotation on Foo will be loaded.)