经过反复试验,我找到了解决方案。对于任何感兴趣的人,这里是:
事实证明,泛型类实际上并没有我担心的那么严重。具有讽刺意味的是,通常令人讨厌的 Java 编译时解释最终对我们有利:实际上,创建一个只有 Object 作为泛型类型的 LinkedHashMap 就足够了。
但是,确实需要注意确保存储在地图中的对象被解组为正确的类。这可以很容易地完成,只需为地图的每个条目存储类信息。请注意,仅将整个地图的类信息存储一次是不够的,因为地图的某些条目可能是该类的子类。
private static class LinkedHashMapConverter implements Converter {
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(Class clazz) {
return clazz.equals(LinkedHashMap.class);
}
@Override
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
@SuppressWarnings("unchecked")
LinkedHashMap<Object, Object> map = (LinkedHashMap<Object, Object>) value;
// store each entry
for (Entry<Object, Object> a : map.entrySet()) {
writer.startNode("entry");
// store the key, the value, and the types of both
writer.startNode("keyClass");
context.convertAnother(a.getKey().getClass());
writer.endNode();
writer.startNode("key");
context.convertAnother(a.getKey());
writer.endNode();
writer.startNode("valueClass");
context.convertAnother(a.getValue().getClass());
writer.endNode();
writer.startNode("value");
context.convertAnother(a.getValue());
writer.endNode();
writer.endNode();
}
}
@SuppressWarnings("rawtypes")
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
LinkedHashMap<Object, Object> res = new LinkedHashMap<Object, Object>();
while (reader.hasMoreChildren()) {
reader.moveDown();
// load the key, the value, and the types of both
reader.moveDown();
Class keyClass = (Class) context.convertAnother(res, Class.class);
reader.moveUp();
reader.moveDown();
Object key = context.convertAnother(res, keyClass);
reader.moveUp();
reader.moveDown();
Class valueClass = (Class) context.convertAnother(res, Class.class);
reader.moveUp();
reader.moveDown();
Object value = context.convertAnother(res, valueClass);
reader.moveUp();
res.put(key, value);
reader.moveUp();
}
return res;
}
}