XStream
基本概述
XStream是一个Java对象和XML相互转换的工具包,提供了所有的基础类型、数组、集合等类型直接转换的支持.XStream对象相当Java对象和XML之间的转换器,转换过程是双向.使用XStream 不用任何映射就能实现多数 Java 对象的序列化。在生成的 XML 中对象名变成了元素名,类中的字符串组成了 XML 中的元素内容。使用 XStream 序列化的类不需要实现 Serializable 接口。XStream 是一种序列化工具而不是数据绑定工具,就是说不能从 XML 或者 XML Schema Definition (XSD) 文件生成类。
特点
XStream 不关心序列化/逆序列化的类的字段的可见性。
序列化/逆序列化类的字段不需要 getter 和 setter 方法。
序列化/逆序列化的类不需要有默认构造函数。
不需要修改类,使用 XStream 就能直接序列化/逆序列化任何第三方类
使用限制
JDK版本不能<1.5.
虽然预处理注解是安全的,但自动侦查注解可能发生竞争条件.
使用场景
Transport 转换
Persistence 持久化对象
Configuration 配置
Unit Tests 单元测试
需要的jar包
xpp3_min-1.1.4c.jar
xstream-1.3.jar
示例
public class Employee {
private String name;
private String designation;
private String department;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Name : " + this.name + "\nDesignation : " + this.designation
+ "\nDepartment : " + this.department;
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.thoughtworks.xstream.*;
public class Writer {
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Jack");
e.setDesignation("Manager");
e.setDepartment("Finance");
XStream xs = new XStream();
try {
FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt");
xs.toXML(e, fs);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class Reader {
public static void main(String[] args) {
XStream xs = new XStream(new DomDriver());
Employee e = new Employee();
try {
FileInputStream fis = new FileInputStream("c:/temp/employeedata.txt");
xs.fromXML(fis, e);
System.out.println(e.toString());
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}