繁体   English   中英

有边界类型参数以注释为边界

[英]Bounded Type Parameters bounded by an annotation

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

public class Box<T extends MyClass> {
    T t
    ...
}

无论如何,我可以通过注释来绑定,以便T的值只能是具有特定注释的类吗?

从Java 8开始,您可以编写

public class Box<T extends @MyAnno MyClass> {
...
}

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

不幸的是,没有办法用Java AFAIK来表达它。 在某些情况下, <T annotatedWith MyAnnotation>会很方便,但是会添加一个新的关键字,说实话,泛型已经足够困难了;)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM