我们用XMLEncoder和XMLDecoder来序列化和反序列化一个类。

我觉得需要注意的是,我们在new一个对象的时候,XMLEncoder本身默认的是类中无参的构造函数,我今儿在实现的时候,老是报出exception,原来是我用有参的构造函数new了对象,改成set方法设置值,就ok了。

需要序列化的类:

package com.test.Bean;

import java.io.Serializable;

public class Customer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Customer(){ } public Customer(String name, int age){
this.name = name;
this.age = age; } public String toString(){
return "name=" + name + ", age=" + age;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }

  XMLEncoder和XMLDecoder的工具类:

package com.test.Serializable;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException; public class BeanXML { public static String encodeBean(Object bean){
ByteArrayOutputStream out = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(out);
encoder.writeObject(bean);
encoder.close();
return out.toString();
} public static Object decodeBean(String xml){
XMLDecoder decoder;
try {
decoder = new XMLDecoder(new ByteArrayInputStream(xml.getBytes("GBK")));
return decoder.readObject();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} }

 测试类:

package com.test.Serializable;
import com.citi.test.Bean.Customer; public class TestBeanXML { public static void main(String[] args){
Customer customer = new Customer();
customer.setName("Ruth");
customer.setAge(10);
BeanXML testBeanXml = new BeanXML();
testBeanXml.encodeBean(customer);
//testBeanXml.decodeBean("ruth.xml");
System.out.print(testBeanXml.encodeBean(customer)); // testBeanXml.decodeBean(testBeanXml.encodeBean(customer));
// System.out.println(testBeanXml.decodeBean(testBeanXml.encodeBean(customer)).getClass()); Customer cust = (Customer) testBeanXml.decodeBean(testBeanXml.encodeBean(customer));
System.out.print(cust.getName()+cust.getAge());
} }

  测试结果:

关于XMLEncoder和XMLDecoder-LMLPHP

04-25 19:42