Java 泛型类型和反射

发布于 2024-10-09 16:15:05 字数 973 浏览 0 评论 0原文

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

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)

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

谢谢。

I have some tricky generic type problem involving reflection. Here's the code.

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!
}

The run() method above will not compile because of the following error.

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

If I remove the wild cards, then it compiles and works fine. What would be the propert way to declare the type parameter for the vairable validatorClass?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷到爆炸 2024-10-16 16:15:05

<代码>? extends Annotation 表示“注释的未知子类型”,它与“注释的任何子类型”不同。

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

类似的问题是此处的答案

? extends Annotation means "unknown subtype of Annotation" which is different from "any subtype of Annotation".

The initialization of the method requires "unknown subtype of Annotation", says at some point the unknown subtype is now known as AnotherAnnotation, and you are trying to pass an object of Annotation class which may not be the type of AnotherAnnotation so they are imcompatible.

Similar question was answer here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文