java - 带注释的泛型由注释注释

标签 java generics interface annotations

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

@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/

相关文章:

java - 如何自定义泛型?

java - 哪个版本的 FindBugs 可以在 Java 1.4 上运行?

java - Eclipse java lwjgl java.library.path 中没有 lwjgl

c# - 实现通用接口(interface)时奇怪的 C# 行为

c# - 绑定(bind)到值类型的通用类型参数 - 使它们可以为空

java - 类 Cast Exception Generics Reflection ParameterizedType

java - 在 HashSet 中存储坐标

java - 使用 jsf 准备向导流程

java - 空接口(interface) - 对象关系建模

c++ - 静态接口(interface) - CRTP?混合?其他?