简体   繁体   English

带注解的泛型由注解注释

[英]Generics with annotation annotated by annotation

I am trying to do this, I have some "base" annotation 我正在尝试这样做,我有一些“基本”注释

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

}

and I have annotaion B which is annotated by A 而且我有注释B由A注释

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

    String value();
}

I want to have interface which behaves something like this, being sure that T is annotation which is annotated by A. 我想让接口表现得像这样,确保T是由A注释的注释。

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

So that I implement that something like this 这样我就实现了这样的事情

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

How to do that? 怎么做? When I use "T extends A" in SomeInterface, when I implement that, it says that B is not a valid substitue. 当我在SomeInterface中使用“ T扩展A”时,当我实现它时,它表示B不是有效的替代。

Thanks! 谢谢!

B is not a valid substitution for <T extends A> because B does not extend A . B不是<T extends A>的有效替代,因为B不扩展A

Java does not include a way to require that a generic type parameter has a particular annotation. Java没有包括要求通用类型参数具有特定注释的方法。

If you can refactor SomeInterface to be a class instead of an interface, you could put a runtime check in the constructor: 如果可以将SomeInterface重构为类而不是接口,则可以在构造函数中添加运行时检查:

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

Annotation inheritance is not possible in Java. 注释继承在Java中是不可能的。

What you have written is simply an annotation annotated by another annotation, not an annotation extending another one. 您编写的内容仅仅是由另一个注释注释的注释,而不是扩展另一个注释的注释。

If annotation inheritance would have been possible, I guess it would have been something like this: 如果注释继承是可能的,那么我想应该是这样的:

public @interface B extends A {

    String value();
}

But it just does not exist. 但是它根本不存在。

Check also this link and this link 还要检查此链接和此链接

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

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