我创建了这个内存类:
public class Memory {
private final Hashtable<String, String> data;
private final Gson gson;
public Memory() {
this.data = new Hashtable<String, String>();
this.gson = new Gson();
}
public <T> void set(String key, List<T> value) {
this.data.put(key, this.gson.toJson(value));
}
public <T> List<T> get(String key, Class<T> cls) {
Type type = new TypeToken<List<T>>() {}.getType();
return this.gson.fromJson(this.data.get(key), type);
}
}
我可以在 json 中存储泛型类型列表然后反序列化它们。
但是当我尝试使用它时,例如这样:
public class User {
private int id;
private String username;
public User() { }
public User(int id, String username) {
this.id = id;
this.username = username;
}
}
Memory memory = new Memory();
List<User> users = new ArrayList<User>();
// add users
memory.set("users", users);
// now get the users back
List<User> copy = memory.get("users", User.class);
Gson 返回 StringMap 的 ArrayList 而不是 Users。
这显然与我正在使用的泛型有关,但是有没有办法绕过它?
谢谢。