我正在尝试这样做,我有一些"base“注释
@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不是一个有效的替代品。
谢谢!
发布于 2015-01-23 06:41:08
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");
}https://stackoverflow.com/questions/28099877
复制相似问题