我有这个编译问题:
这是有问题的课程:
package huru.entity;
import io.vertx.core.json.JsonObject;
import java.util.Date;
public class BaseEntity <T extends BaseModel> extends JsonObject {
private T model;
public BaseEntity(T m){
this.model = m;
}
public void setUpdateInfo(String user){
this.model.updatedBy = user;
this.model.updatedAt = new Date();
}
public JsonObject toJsonObject(){
return JsonObject.mapFrom(this.model);
}
public T getEntityType (){
return this.model.getClass(); // doesn't compile
}
}
Run Code Online (Sandbox Code Playgroud)
我也试过用
public T getEntityType (){
return T; // doesn't compile
}
Run Code Online (Sandbox Code Playgroud)
但这显然也无效.有谁知道如何返回该泛型类的类实例?
我也试过这个:
public Class<T> getEntityType (){
return this.model.getClass();
}
Run Code Online (Sandbox Code Playgroud)
我得到:
然后我尝试了这个:
public Class<? extends T> getEntityType (){
return this.model.getClass();
}
Run Code Online (Sandbox Code Playgroud)
我有:
你似乎很困惑.你将返回代表T的类,而不是T.
让我们用字符串替换T并说明你为什么做的事情毫无意义:
private String model;
public String getEntityType() {
return model.getClass();
// Of course this does not work; model.getClass() is not a string!
}
public String getEntityType() {
return String;
// This doesn't even compile.
}
Run Code Online (Sandbox Code Playgroud)
为了解释,这个:
public T getEntityType() {
....
}
Run Code Online (Sandbox Code Playgroud)
要求你返回任何T的实际实例.不是T代表的任何类型.就像'String'意味着你应该返回一个String的实际实例,而不是String的概念,类型.
也许你打算这样做:
public T getEntityType() {
return model;
}
Run Code Online (Sandbox Code Playgroud)
或者更可能的是,鉴于您将此方法命名为"getEntityType",您的意思是:
public Class<? extends T> getEntityType() {
return model.getClass();
}
Run Code Online (Sandbox Code Playgroud)
是的,? extends T因为模型是T或T的任何子类型.