通过 Xstream 的变量初始化 [英] Variable initialization past Xstream

查看:32
本文介绍了通过 Xstream 的变量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下声明视为 SomeClass

private Set<String> blah    = new HashSet<String>();

在一个班级中制作的,这是后来的

Made in a class, which is later

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);

StringBuilder json = new StringBuilder(xstream.toXML(SomeClass));

rd = (SomeClass) xstream.fromXML(json.toString());

当我@Test

assertTrue(rd.getBlah().size() == 0);

我在 rd.getBlah()

当我不是预先初始化,而是将初始化放置到 SomeClass

When I, instead of initializing up front, place initialization to a constructor of SomeClass

public SomeClass() {
  blah = new HashSet<String>();
}

同样的问题 - rd.getBlah()

当我修改 getter 以首先检查 null 时,它可以工作,但是 ..

When i modify the getter to check for null first, it works, but ..

public Set<String> getBlah() {
   if (blah == null)
      return new HashSet<Sgring>();
   return blah;
}

我很纳闷...为什么XStream不初始化变量,是否需要延迟实例化?

I am puzzled ... Why does XStream not initialize variables and whether lazy instantiation is necessary?

推荐答案

XStream 使用与 JDK 序列化相同的机制.当使用具有优化反射 API 的增强模式时,它不会调用默认构造函数.解决方法是实现 readResolve 方法如下:

XStream uses the same mechanism as the JDK serialization. When using the enhanced mode with the optimized reflection API, it does not invoke the default constructor. The solution is to implement the readResolve method as below:

public class SomeClass{
    private Set<String> blah;

    public SomeClass(){
        // do stuff
    }

    public Set<String> getBlah(){
        return blah;
    }

    private Object readResolve() {
        if(blah == null){
            blah = new HashSet<String>();
        }
        return this;
    }
}

参考

这篇关于通过 Xstream 的变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆