XSTream short dynamic aliases

I want to have short names for classes, now I can do it with aliases

XStream x = new XStream(); x.alias("dic", Dic.class); 

but I have to define an alias manually for each class, is there a way to configure xstream for this automatically?

+4
source share
3 answers

Internally, XStream uses its Mapper interface to handle the mapping of classes and fields to their corresponding XML names. There are many implementations of this interface. The XStream class itself can accept the Mapper in its constructor. You might want to check the source code of this class to see which Mapper implementation is used by default, and then write your own implementation that will automatically make your aliases for you. ClassAliasingMapper looks useful, for example.

+3
source

As I decided:

1.- When I create xstream, I override its wrapmapper method

 XStream xstream = new XStream() { @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MyClassAliasingMapper(next); } }; 

2.- s

 public class MyClassAliasingMapper extends ClassAliasingMapper { public MyClassAliasingMapper(Mapper wrapped) { super(wrapped); } @Override public Class realClass(String elementName) { try { return <… your own class …> } catch (Exception e) { // do nothing we fall back on super implementation } return super.realClass(elementName); } @Override public String serializedClass(Class type) { try { return <… your own element name …> } catch (Exception e) { // do nothing we fall back on super implementation } return super.serializedClass(type); } } 
+6
source

The only alternative is to use XStream annotations :

 package com.my.incredibly.long.package.name; @XStreamAlias("dic") public class Dic { ... 

Then in your code, where you configure XStream:

 xstream.processAnnotations(Dic.class); // OR xstream.autodetectAnnotations(true); 

The problem is that XStream already knows its aliases to deserialize your classes, so autodetectAnnotations(true) will NOT help if you cannot guarantee that you will serialize the class before deserializing. Plus (and this may or may not be a problem for you), you introduce an explicit XStream dependency with your objects.

I put the tags of all the classes that I need, are serialized (here are several options: annotate them via XStream or my own annotation, embed the marker interface in them, capture all classes from a specific package (s)), auto-detect them to load, and explicitly configure the XStream instance for an alias as a class name without a package name.

+5
source

All Articles