gpt4 book ai didi

Java 泛型类型和反射

转载 作者:行者123 更新时间:2023-11-30 05:07:38 24 4
gpt4 key购买 nike

我有一些涉及反射的棘手泛型类型问题。这是代码。

public @interface MyConstraint {
Class<? extends MyConstraintValidator<?>> validatedBy();
}

public interface MyConstraintValidator<T extends Annotation> {
void initialize(T annotation);
}

/**
@param annotation is annotated with MyConstraint.
*/
public void run(Annotation annotation) {
Class<? extends MyConstraintValidator<? extends Annotation>> validatorClass = annotation.annotationType().getAnnotation(MyConstraint.class).validatedBy();
validatorClass.newInstance().initialize(annotation) // will not compile!
}

由于出现以下错误,上面的 run() 方法将无法编译。

The method initialize(capture#10-of ? extends Annotation) in the type MyConstraintValidator<capture#10-of ? extends Annotation> is not applicable for the arguments (Annotation)

如果我删除通配符,则它可以编译并正常工作。为 vairable validatorClass 声明类型参数的正确方法是什么?

谢谢。

最佳答案

? extends Annotation 表示“注释的未知子类型”,它不同于“注释的任何子类型”。

该方法的初始化需要“注释的未知子类型”,表示在某些时候未知子类型现在被称为 AnotherAnnotation,并且您试图传递 Annotation 类的对象,但该对象可能不会是 AnotherAnnotation 的类型,因此它们不兼容。

类似问题的回答here .

关于Java 泛型类型和反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com