我需要为一些对象实现JSON序列化,并且在与泛型集合集成时遇到了问题.
所有可序列化类都实现此接口(JSONObject来自this库):
interface JSONSerializable{
public JSONObject dump() throws JSONException //serializes object
public void load(JSONObject obj) throws JSONException //deserializes object
}
我的基于java.util.list的集合的代码大致如下所示:
class AwesomeList<T extends JSONSerializable> implements JSONSerializable{
private LinkedList<T> items = new LinkedList<T>();
...
...
public JSONObject dump() throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray();
for(T i : items){
a.put(i.dump());
}
result.put("items", a);
return result;
}
public void load(JSONObject obj) throws JSONException{
//here is my problem
}
}
我的问题是:当我从JSONObject加载AwesomeList时,我需要创建它的元素,但这是不可能的,因为java禁止我编写
T newItem = new T();
newItem.load(obj);
我应该如何修改我完成这项任务的方法?