我正在尝试这样做,我有一些“基础”注释
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface A
{
}
我有一个由 A 注释的注释 B
@A
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface B {
String value();
}
我想要一个行为类似这样的接口(interface),确保 T 是由 A 注释的注释。
interface SomeInterface<T extends A>
{
void method(T argument);
}
这样我就可以像这样实现
public class Implementation implements SomeInterface<B>
{
public void method(B argument);
}
该怎么做?当我在 SomeInterface 中使用“T extends A”时,当我实现它时,它说 B 不是有效的替代品。
谢谢!
最佳答案
B
不是 <T extends A>
的有效替代因为B
不扩展 A
.
Java 不包含要求泛型类型参数具有特定注释的方法。
如果你能重构SomeInterface
要成为类而不是接口(interface),您可以在构造函数中进行运行时检查:
protected SomeInterface(Class<T> classOfT) {
if(classOfT.getAnnotation(A.class) == null)
throw new RuntimeException("T must be annotated with @A");
}
关于java - 带注释的泛型由注释注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099877/