Java – you can write generic xmladapters
•
Java
I know that I can use raw type to write XML adapter, but I can use generic type I tried to read the API, but I didn't even notice the clue
For example, map:
I want to use, for example:
@XmlJavaTypeAdapter(GenericMapAdapter<String,Double>.class)// private final HashMap<String,Double> depWageSum = // new HashMap<String,Double>();
To get
<depWageSum> <entry key="RI">289.001</entry> <entry key="VT">499.817</entry> <entry key="HI">41.824</entry> ... <depWageSum>
The class itself may look like the following lines:
@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)));}}; } }
Solution
You will not be able to perform this operation as described Class does not retain type parameters However, you can introduce some simple subclasses that can take advantage of the logic in genericmapadapter:
public class StringDoubleMapAdapter extends GenericMapAdapter<String,Double> { }
Then use the adapter subclass on the property:
@XmlJavaTypeAdapter(StringDoubleMapAdapter.class)// private final HashMap<String,Double>();
For more information about xmladapters, see:
> http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码