我知道,我可以使用原始类型来编写XMLAdapter,但是我可以使用泛型类型吗?我试着阅读接口( link ),但没有注意到这方面的线索。
例如map:
我想使用类似这样的东西:
@XmlJavaTypeAdapter(GenericMapAdapter<String, Double>.class)//
private final HashMap<String, Double> depWageSum = //
new HashMap<String, Double>();要获得
<depWageSum>
<entry key="RI">289.001</entry>
<entry key="VT">499.817</entry>
<entry key="HI">41.824</entry>
...
<depWageSum>而类本身可能看起来像这样:
@SuppressWarnings("serial") public class GenericMapAdapter<K, V> extends XmlAdapter<GenericMapAdapter.MapType<K, V>, Map<K, V>> {
public static class MapType<K, V> {
@XmlValue protected final List<MapTypeEntry<K, V>> entry = new ArrayList<MapTypeEntry<K, V>>();
public static class MapTypeEntry<K, V> {
@XmlAttribute protected K key;
@XmlValue protected V value;
private MapTypeEntry() {};
public static <K, V> MapTypeEntry<K, V> of(final K k, final V v) {
return new MapTypeEntry<K, V>() {{this.key = k; this.value = v;}};
} } }
@Override public Map<K, V> unmarshal(final GenericMapAdapter.MapType<K, V> v) throws Exception {
return new HashMap<K, V>() {{ for (GenericMapAdapter.MapType.MapTypeEntry<K, V> myEntryType : v.entry)
this.put(myEntryType.key, myEntryType.value);}};
}
@Override public MapType<K, V> marshal(final Map<K, V> v) throws Exception {
return new GenericMapAdapter.MapType<K, V>() {{for (K key : v.keySet())
this.entry.add(MapTypeEntry.of(key, v.get(key)));}};
} }发布于 2010-12-03 22:12:36
您将无法按照所述方式执行此操作。类型参数将不会被类保留。但是,您可以引入一些简单的子类,它们可以利用GenericMapAdapter中的逻辑:
public class StringDoubleMapAdapter extends GenericMapAdapter<String, Double> {
}然后在属性上使用适配器子类:
@XmlJavaTypeAdapter(StringDoubleMapAdapter.class)//
private final HashMap<String, Double> depWageSum = //
new HashMap<String, Double>();有关XmlAdapter的更多信息,请参阅:
https://stackoverflow.com/questions/4338237
复制相似问题