Java 由注释限定的限定类型参数

Java 由注释限定的限定类型参数,java,generics,annotations,Java,Generics,Annotations,在Java中,可以使边界类型参数必须从特定的类或接口扩展,例如 public class Box<T extends MyClass> { T t ... } 公共类框{ T T ... } 我是否可以通过注释进行绑定,使T的值只能是具有特定注释的类?不幸的是,没有办法用java AFAIK来表达它在某些情况下非常方便,但它会添加一个新的关键字,老实说,泛型已经足够困难了;) 否则,对于注释,@duckstep说,在运行时使用 t.getClass().isAnn

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

public class Box<T extends MyClass> {
    T t
    ...
}
公共类框{
T T
...
}

我是否可以通过注释进行绑定,使T的值只能是具有特定注释的类?

不幸的是,没有办法用java AFAIK来表达它<代码>在某些情况下非常方便,但它会添加一个新的关键字,老实说,泛型已经足够困难了;)

否则,对于注释,@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());
}

从Java8开始,您可以编写

public class Box<T extends @MyAnno MyClass> {
...
}
公共类框{
...
}

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

我认为您不能,但您可以让这些类实现标记接口(一个没有方法的接口)。我很确定一些持久性框架可以做到这一点,而且它们必须在运行时完成。我认为您可以使用,但这将是额外的语言,而且也相当复杂。在运行时检查很简单:
t.getClass().isAnnotationPresent(annotationClass)