Java 从类创建对象<&燃气轮机;
最终,我需要能够在我的代码中做到这一点:Java 从类创建对象<&燃气轮机;,java,Java,最终,我需要能够在我的代码中做到这一点: User result = goo.getEntity("users", "id1").getAs(User.class); 但是,在上面的代码中,我需要显式地将getEntity的结果强制转换为User,方法是什么,以便getAs的返回类型将是whatever.class 以下是底层psuedo代码: public class EntityType { Map json = null; public EntityType(Map
User result = goo.getEntity("users", "id1").getAs(User.class);
但是,在上面的代码中,我需要显式地将getEntity
的结果强制转换为User
,方法是什么,以便getAs
的返回类型将是whatever.class
以下是底层psuedo代码:
public class EntityType {
Map json = null;
public EntityType(Map json){
this.json = json;
}
public Class<?> getAs(Class<?> clazz){
// create clazz object from json map
}
}
public EntityType getEntity(String kind, String id){
Map json = getFromServer(kind, id);
EntityType entity = new EntityType(json);
return entity;
}
公共类EntityType{
Map json=null;
公共EntityType(映射json){
this.json=json;
}
公共类getAs(类clazz){
//从json映射创建clazz对象
}
}
public EntityType getEntity(字符串类型,字符串id){
Map json=getFromServer(种类,id);
EntityType实体=新的EntityType(json);
返回实体;
}
应该是
public <T> T getAs(Class<T> clazz) {
public T getAs(类clazz){
注意:您将返回分配为User result=
,返回类型应为T
,而不是Class
公共类EntityType{
Map json=null;
公共EntityType(映射json){
this.json=json;
}
公共课(课堂){
if(类实例(本)){
返回(T)这个;
}
返回null;
}
}
也就是说,没有编译器错误。但是,当我运行时,我得到了InstanceException。您可以发布stacktrace吗?在getAs方法中传递的类实际上并不是从EntityType扩展而来的
public class EntityType {
Map json = null;
public EntityType(Map json){
this.json = json;
}
public <T extends EntityType> T getAs(Class<T> clazz){
if(clazz.isInstance(this)) {
return (T) this;
}
return null;
}
}