XStream short dynamic aliases

我与影子孤独终老i 提交于 2019-11-30 21:50:37

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.

They way I solved is:

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.- with

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's 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's implementation
        }
        return super.serializedClass(type);
    }
}
ChssPly76

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!