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

查看:16
本文介绍了在维护对 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,它明确定义了 FooFooContainer.
  • 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,则 FooSomeClass 只能在 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天全站免登陆