由注释限定的有界类型参数

在Java中,可以使得bounder类型参数必须从特定类或接口扩展,例如

public class Box { T t ... } 

反正我是否可以通过注释绑定,以便T的值只能是具有特定注释的类?

从Java 8开始,您可以编写

 public class Box { ... } 

与任何Java注释一样,要强制执行语义,您需要使用注释处理器。 Checker Framework是一个为您强制执行语义的注释处理工具:如果您尝试使用缺少@MyAnno注释的类型参数来实例化Box类型,则可以将其配置为发出错误。

不幸的是,没有办法在java AFAIK中表达它。 在某些情况下会非常方便,但它会添加一个新关键字,老实说generics很难;)

否则对于注释,因为@duckstep说在运行时很容易检查

 t.getClass().isAnnotationPresent(annotationClass) 

但是,对于注释处理器来说,API要处理起来要困难得多。 这是一些代码,如果它可以帮助一些人:

 private boolean isAnnotationPresent(TypeElement annotationTypeElement, String annotationName) { for (AnnotationMirror annotationOfAnnotationTypeMirror : annotationTypeElement.getAnnotationMirrors()) { TypeElement annotationOfAnnotationTypeElement = (TypeElement) annotationOfAnnotationTypeMirror.getAnnotationType().asElement(); if (isSameType(annotationOfAnnotationTypeElement, annotationName)) { return true; } } return false; } private boolean isSameType(TypeElement annotationTypeElement, String annotationTypeName) { return typeUtils.isSameType(annotationTypeElement.asType(), elementUtils.getTypeElement(annotationTypeName).asType()); }