我有一组由4个类组成的类,它们表示我的数据库对象(数据库目前只是一个ArrayList)。
我使用GSON将这些对象存储在.txt文件中。
一个名为Storage的类负责读取这些对象并将其写入这些.txt文件。
我的问题是:我有一个通用对象T extends MyInterface。该对象表示4个数据库类。我将T放在Storage方法中,以便只对任何数据库对象使用这个类。以下是代码:
public class Storage<T extends MyInterface> {
Gson GSON = new Gson();
public ArrayList<T> readAll() {
String objectsJSON = TextFileHandler.readFromFile(fileStorageLocation); // This works
System.out.println(objectsJSON); // This also works (prints out correctly)
Type collectionType = new TypeToken<ArrayList<T>>() {}.getType();
return GSON.fromJson(objectsJSON, collectionType); // This fails
}
}我得到以下例外:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to
interfaces.MyInterface
你们知道会是什么吗?
发布于 2020-08-12 19:36:04
匿名TypeToken子类型的全部要点是在编译时定义它们,以便保存泛型类型信息。您需要做一些事情来使令牌信息动态可用。这种方法可能会起作用:
private final TypeToken<ArrayList<T>> targetType;
public Storage(Class<T> dataType) {
targetType = new TypeToken<ArrayList<T>>(){}
.where(new TypeParameter<T>(){}, dataType);
}
public List<T> readAll() { // avoid using concrete ArrayList in public API;
// not a bad idea to change it in the other locations
...
return GSON.fromJson(objectsJson, targetType);
}发布于 2020-08-12 20:31:15
您应该使用接口List,而不是将该实现用作ArrayList。
public List<T> readAll() {
String objectsJSON = TextFileHandler.readFromFile(fileStorageLocation);
System.out.println(objectsJSON);
Type collectionType = new TypeToken<List<T>>() {}.getType();
return GSON.fromJson(objectsJSON, collectionType);
}如果这不起作用,请检查objectJSON格式是否正确。
发布于 2020-08-13 15:11:27
对于任何想要找到答案的人来说,以下是我为解决这个问题所做的努力:
问题是,GSON不知道要实例化哪个类,因为我的Storage<T>被用于几个不同的实体。我不得不以某种方式告诉它,Storage<T>使用的每个实例都是哪个特定的实体类。我所犯的错误是:
Cannot cast LinkedTreeMap to MyInterface.
因为在运行时,Storage不知道要实例化哪个类。
我正在做一个常规的Java项目,所以我下载了Guava.jar并将它添加到我的项目中:http://search.maven.org/remotecontent?filepath=com/google/guava/guava/23.0/guava-23.0.jar
我修改了我的泛型类Storage<T>构造函数,以接受Class<T> dataType参数,以便它能够在运行时知道它用于哪个类。我还添加了一个私有字段TypeToken<List<T>>,这样它就可以存储有关反序列化类的信息。
基本上,我所做的就是:
import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import com.google.gson.*;
public class Storage<T extends MyInterface> {
// This was used so the Storage objects knows which dataType it's associated to
// Because T is deleted at runtime, so you can't use that.
private TypeToken<List<T>> targetDataType;
// I changed the constructor to take in 1 bonus argument
public Storage(Class<T> dataType) {
targetDataType = new TypeToken<List<T>>() {}
.where(new TypeParameter<T>() {}, dataType);
}
public List<T> deserialize() {
// Read JSON data into a <jsonString> variable
Gson GSON = new Gson();
return GSON.fromJson(jsonString, targetDataType.getType());
}
}https://stackoverflow.com/questions/63383526
复制相似问题