После нескольких проб и ошибок, я нашел решение. Для всех, кого это интересует, вот оно:
Оказывается, что классы, являющиеся общими, на самом деле не такие большие проблемы, как я боялся. По иронии судьбы, интерпретация времени компиляции Java, которая, как правило, вызывает раздражение, в конечном итоге приносит нам пользу: на самом деле достаточно создать 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;
}
}
Это работает, только если Карта всегда имеет тип. Как насчет общего случая? –