简体   繁体   English

Java递归泛型类通配符匹配

[英]Java recursive generics class wildcard matching

Having these generic interface and class: 具有以下通用接口和类:

interface TestIntf<T extends TestIntf<T>> 
{
    void test(T param);
}

class TestImpl<T extends TestIntf<T>> implements TestIntf<T> 
{
    @Override
    public void test(T param) { System.out.println(param); }
}

This fails: 这将失败:

Class<? extends TestIntf<?>> clz = TestImpl.class;

(Type mismatch: cannot convert from Class<TestImpl> to Class<? extends TestIntf<?>> ) (类型不匹配:无法从Class<TestImpl>转换为Class<? extends TestIntf<?>>

Why? 为什么? How to properly provide a reference to TestImpl class to match Class<? extends TestIntf<?>> 如何正确提供对TestImpl类的引用以匹配Class<? extends TestIntf<?>> Class<? extends TestIntf<?>> ? Class<? extends TestIntf<?>>

You can't. 你不能 Use an unsafe cast. 使用不安全的演员表。

Class<? extends TestIntf<?>> clz = (Class<? extends TestIntf<?>>) TestImpl.class;

or don't use the inner generics: 或不使用内部泛型:

Class<? extends TestIntf> clz = TestImpl.class;

Update: When it regards annotations, there is nothing you can do - the annotation has to be changed. 更新:关于注释,您无能为力-必须更改注释。 You cannot have a class literal represent a generic type. 您不能让类文字代表泛型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM