gpt4 book ai didi

java - 序列化 java.lang.Locale

转载 作者:行者123 更新时间:2023-12-03 00:57:13 25 4
gpt4 key购买 nike

得到一个类,它可以使用 XMLEncoder 很好地序列化为 xml,其中包含所有变量。除了保存 java.util.Locale 的那个。可能有什么技巧?

最佳答案

问题是 java.util.Locale 不是 bean 。来自 XMLEncoder文档:

The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects.

但是,API 允许您使用 PersistenceDelegates 来序列化非 bean 类型:

示例 bean:

public class MyBean implements Serializable {

private static final long serialVersionUID = 1L;

private Locale locale;
private String foo;

public MyBean() {
}

public Locale getLocale() {
return locale;
}

public void setLocale(Locale locale) {
this.locale = locale;
}

public String getFoo() {
return foo;
}

public void setFoo(String foo) {
this.foo = foo;
}

}

序列化包含区域设置类型的数据图:

public class MyBeanTest {

public static void main(String[] args) throws Exception {
// quick and dirty test

MyBean c = new MyBean();
c.setLocale(Locale.CHINA);
c.setFoo("foo");

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(outputStream);
encoder.setPersistenceDelegate(Locale.class, new PersistenceDelegate() {
protected Expression instantiate(Object oldInstance, Encoder out) {
Locale l = (Locale) oldInstance;
return new Expression(oldInstance, oldInstance.getClass(),
"new", new Object[] { l.getLanguage(), l.getCountry(),
l.getVariant() });
}
});
encoder.writeObject(c);
encoder.flush();
encoder.close();

System.out.println(outputStream.toString("UTF-8"));

ByteArrayInputStream bain = new ByteArrayInputStream(outputStream
.toByteArray());
XMLDecoder decoder = new XMLDecoder(bain);

c = (MyBean) decoder.readObject();

System.out.println("===================");
System.out.println(c.getLocale());
System.out.println(c.getFoo());
}

}

这是描述如何在反序列化时实例化对象的代码部分 - 它将构造函数参数设置为三个字符串值:

    new PersistenceDelegate() {
protected Expression instantiate(Object oldInstance, Encoder out) {
Locale l = (Locale) oldInstance;
return new Expression(oldInstance, oldInstance.getClass(),
"new", new Object[] { l.getLanguage(), l.getCountry(),
l.getVariant() });
}
}

阅读Using XMLEncoder作者:Philip Milne,了解更多信息。

除此之外,以文本形式存储区域设置信息并在需要时使用它来查找适当的 Locale 对象可能会更明智。这样,您在序列化对象时不需要特殊情况代码并使其更加可移植。

关于java - 序列化 java.lang.Locale,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/195587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com