繁体   English   中英

带注解的泛型由注解注释

[英]Generics with annotation annotated by annotation

我正在尝试这样做,我有一些“基本”注释

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface A
{

}

而且我有注释B由A注释

@A
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface B {

    String value();
}

我想让接口表现得像这样,确保T是由A注释的注释。

interface SomeInterface<T extends A>
{
    void method(T argument);
}

这样我就实现了这样的事情

public class Implementation implements SomeInterface<B>
{
    public void method(B argument);
}

怎么做? 当我在SomeInterface中使用“ T扩展A”时,当我实现它时,它表示B不是有效的替代。

谢谢!

B不是<T extends A>的有效替代,因为B不扩展A

Java没有包括要求通用类型参数具有特定注释的方法。

如果可以将SomeInterface重构为类而不是接口,则可以在构造函数中添加运行时检查:

protected SomeInterface(Class<T> classOfT) {
    if(classOfT.getAnnotation(A.class) == null)
        throw new RuntimeException("T must be annotated with @A");
}

注释继承在Java中是不可能的。

您编写的内容仅仅是由另一个注释注释的注释,而不是扩展另一个注释的注释。

如果注释继承是可能的,那么我想应该是这样的:

public @interface B extends A {

    String value();
}

但是它根本不存在。

还要检查此链接和此链接

暂无
暂无

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

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