一些试验和错误之后,我找到了解决办法。对于任何感兴趣的人来说,这里是:
事实证明,泛型类实际上并不像我担心的那么多。具有讽刺意味的是,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;
}
}
仅当Map始终为类型时才有效。一般情况如何? –