Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从类创建对象<&燃气轮机;_Java - Fatal编程技术网

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