![](/img/trans.png)
[英]Incomparable types: java.lang.Class<capture#1 of ? extends T[]> and java.lang.Class<java.lang.Object[]>
[英]Inconvertible types; cannot cast 'caputure<? extends IEntity>'to 'java.lang.Class<T>'
共有三個 class,class IEntity 是一個抽象的 class,僅用於泛型。
Class 一:
public abstract class IEntity {
}
class 二:
public class Config {
private Class<? extends IEntity> clazz;
public Class<? extends IEntity> getClazz(){
return this.clazz;
}
}
class 三:
public class EntityTest<T extends IEntity> {
private Class<T> clazz;
public void init(Config config){
//Here is the wrong report
// Failed to compile
this.clazz=config.getClazz();
}
}
看來你還沒有理解<? extends IEntity>
<? extends IEntity>
和<T extends IEntity>
。
讓我們介紹IEntity
的兩個子類,以及Config
的構造函數以便更清楚地解釋:
class Entity1 extends IEntity {}
class Entity2 extends IEntity {}
// in Config class
public Config(Class<? extends IEntity> clazz) {
this.clazz = clazz;
}
在這一行this.clazz=config.getClazz();
,您正在嘗試分配一個Class<? extends IEntity>
Class<? extends IEntity>
為Class<T>
,其中T
是IEntity
或IEntity
本身的子類。 問題是,我們不知道究竟是什么類型的 class getClazz
返回。 它可以是Class<Entity1>
或Class<Entity2>
。 另一方面,我們確實知道我們需要什么類型 - Class<T>
。 我們如何確保無論getClazz
返回什么類型的 class 與Class<T>
相同? T
可以是Entity2
但getClazz
可以返回Class<Entity2>
,不是嗎?
這是一個帶有代碼的具體示例:
Config c = new Config(Entity1.class);
// c.config now contains Entity1.class
// the line below will attempt to assign an Entity1.class to a variable of type Class<Entity2>
new EntityTest<Entity2>().init(c);
您現在應該明白為什么init
中有錯誤。
確保getClazz
返回與Class<T>
相同類型的 class 的一種方法是使Config
也通用:
class Config<T extends IEntity> {
private Class<T> clazz;
public Class<T> getClazz(){
return this.clazz;
}
}
class EntityTest<T extends IEntity> {
private Class<T> clazz;
public void init(Config<T> config){
this.clazz=config.getClazz();
}
}
<? extend IEntity>
<? extend IEntity>
表示 class 必須是 IEntity 或其子類。 您代碼中的“T”只是 IEntity 的一個子類( <? extend IEntity>
可以有很多子類),您不能確定<? extend IEntity>
<? extend IEntity>
與“T”相同或者是“T”的子類。 所以類型轉換是非法的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.