[英]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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.