views:

328

answers:

2

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 alias manually for every class, is there any way to configure xstream to do it automatically?

+2  A: 

The only other 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, however, is that in order to deserialize your classes XStream has to know their aliases already, so autodetectAnnotations(true) is NOT going to help unless you can guarantee that you will serialize the class prior to deserializing it. Plus (and this may or may not be a concern for you) you're introducing an explicit XStream dependency to your objects.

I've ended up tagging all the classes I need serialized (several choices here: annotate them via XStream or your own annotation; have them implement marker interface; grab all the classes from particular package(s)), autodetecting them on load and explicitly configuring XStream instance to alias them as class name without package name.

ChssPly76
cool idea, i could even get this on domian objects with regex replace of @Entity, however this wont work for me this time, thx any way.
01
+1  A: 

Internally, XStream uses its Mapper interface to handle the mapping of classes and fields to their corresponding names in the XML. There are a large number of implementations of this interface. The XStream class itself can take a Mapper in its constructor. You might want to check out the source code of that class to see which Mapper implementation it uses by default, and then write your own implementation that automatically does your aliasing for you. ClassAliasingMapper looks useful, for example.

skaffman
That would work great if you have a unique bi-directional way to map classes to aliases (e.g if all mapped classes are in the same known package). Otherwise this just adds another level of indirection since you still need to tell your mapper how to map aliases to classes. I'm applying this to my scenario, though - this may work just fine for OP's circumstances.
ChssPly76
I just need to turn objects(not mine) into xml, so this might work great.
01