有界类型参数由注释限定 [英] Bounded Type Parameters bounded by an annotation
问题描述
在 Java 中,可以使边界类型参数必须从特定的类或接口扩展,例如
In Java, it is possible to make a bounder type parameter have to extend from a particular class or interface e.g.
public class Box<T extends MyClass> {
T t
...
}
无论如何我可以通过注释绑定,以便 T 的值只能是具有特定注释的类吗?
Is there anyway I can bound by an annotation so that values of T can only be classes that have a particular annotation?
推荐答案
从Java 8开始,你可以写
Starting in Java 8, you can write
public class Box<T extends @MyAnno MyClass> {
...
}
与任何 Java 注释一样,要强制执行语义,您需要使用注释处理器.Checker Framework 是一种为您强制执行语义的注释处理工具:如果您尝试使用缺少 @MyAnno
注释的类型参数实例化 Box
类型.
As with any Java annotation, to enforce the semantics, you need to use an annotation processor. The Checker Framework is one annotation-processing tool that enforces the semantics for you: you can configure it to issue an error if you ever try to instantiate the Box
type using a type argument that lacks the @MyAnno
annotation.
这篇关于有界类型参数由注释限定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!