Java 如何从Json格式的文件中反序列化通用对象

Java 如何从Json格式的文件中反序列化通用对象,java,json,generics,gson,Java,Json,Generics,Gson,我如何告诉fromJson方法我需要返回T类型的对象? 我知道T级是不可能的 @Override public T getById(String id) { File json = new File(folder, id); JsonReader reader = null; try { reader = new JsonReader(new FileReader(json.getPath())); return gson.fromJson

我如何告诉fromJson方法我需要返回T类型的对象? 我知道T级是不可能的

@Override
public T getById(String id) {
    File json = new File(folder, id);
    JsonReader reader = null;
    try {
        reader = new JsonReader(new FileReader(json.getPath()));
        return gson.fromJson(reader, T.class);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return null;
由于您的泛型参数
在运行时不存在。正如您正确指出的,您不能执行
T.class
,因为没有
T

要执行所需操作,需要请求将与类型参数对应的
对象的实例传递到方法中:

public <T> T getById(final String id, final Class<T> type) {
由于您的泛型参数
在运行时不存在。正如您正确指出的,您不能执行
T.class
,因为没有
T

要执行所需操作,需要请求将与类型参数对应的
对象的实例传递到方法中:

public <T> T getById(final String id, final Class<T> type) {

最后,我做了惯常的把戏(事实证明是这样的)

公共类GenericClass{
私有最终类类型;
公共泛型类(类类型){
this.type=type;
}
公共类getMyType(){
返回此.type;
}

}

最终,我做了惯常的把戏(事实证明是这样的)

公共类GenericClass{
私有最终类类型;
公共泛型类(类类型){
this.type=type;
}
公共类getMyType(){
返回此.type;
}

}

我能用TypeToken做到这一点吗?关键是让一个类负责知道返回什么类的对象,并用OUG类强制转换来完成这件事…@user1685095你不能用泛型做这件事,因为它们在运行时不存在。我能用TypeToken做到这一点吗?关键是让一个类负责知道什么类的对象要返回并使用oug类强制转换来执行这些操作…@user1685095您不能使用泛型,因为它们在运行时不存在。
public class GenericClass<T> {

 private final Class<T> type;

 public GenericClass(Class<T> type) {
      this.type = type;
 }

 public Class<T> getMyType() {
     return this.type;
 }