通过注解界限制类型参数 [英] 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注释,执行语义,你需要使用注释处理器。该检查框架是一个强制的语义为您注解处理工具:您可以配置它,如果发出错误你曾经尝试实例化箱
键入使用缺乏 @MyAnno
注释的类型参数。
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屋!