yan*_*nko 2 java serialization locale
得到了一个类,它与XMLEncoder串行化为xml,其中包含所有变量.除了持有java.util.Locale的那个.可能是什么伎俩?
问题是java.util.Locale不是bean.从XMLEncoder doc:
XMLEncoder类是ObjectOutputStream的补充替代,可用于生成JavaBean的文本表示,其 方式与ObjectOutputStream可用于创建Serializable对象的二进制表示的方式相同.
但是,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;
}
}
Run Code Online (Sandbox Code Playgroud)
序列化包含Locale类型的数据图:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
这是描述如何在反序列化时实例化对象的代码部分 - 它将构造函数参数设置为三个字符串值:
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() });
}
}
Run Code Online (Sandbox Code Playgroud)
阅读使用 Philip Milne的XMLEncoder获取更多信息.
除此之外,以文本形式存储区域设置信息并使用它在需要时查找适当的Locale对象可能更为明智.这样,在序列化对象并使其更具可移植性时,您不需要特殊的大小写代码.
归档时间: |
|
查看次数: |
2820 次 |
最近记录: |