在维护对Java 7的支持的同时使用@Repeatable [英] Using @Repeatable while mainaining support for Java 7

查看:173
本文介绍了在维护对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.

这样的事情是否可能?

Is something like this at all possible?

推荐答案

您需要提供两个版本的库:

You need to provide two versions of your library:


  • 一个用于Java 8的文件,它使用 @Repeatable <对 Foo 的定义
    进行元注释/ code>。

  • 用于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 and FooContainer.

不幸的是,你不能同时支持Java 7和重复注释有一个版本的库。如果您希望客户端能够重复注释,则必须将 Foo 元注释为 @Repeatable java.lang.annotation.Repeatable 仅在Java 8中定义。因此,如果注释 Foo 被元元素注释为 @Repeatable 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.)

这篇关于在维护对Java 7的支持的同时使用@Repeatable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆