使用 XStream 把 Java 對象序列化為 XML
使用 XStream 不用任何映射就能實現(xiàn)多數(shù) Java 對象的序列化。在生成的 XML 中對象名變成了元素名,類中的字符串組成了 XML 中的元素內(nèi)容。使用 XStream 序列化的類不需要實現(xiàn) Serializable 接口。XStream 是一種序列化工具而不是數(shù)據(jù)綁定工具,就是說不能從 XML 或者 XML Schema Definition (XSD) 文件生成類。
和其他序列化工具相比,XStream 有三個突出的特點:
1. XStream 不關(guān)心序列化/逆序列化的類的字段的可見性。
2. 序列化/逆序列化類的字段不需要 getter 和 setter 方法。
3. 序列化/逆序列化的類不需要有默認構(gòu)造函數(shù)。
不需要修改類,使用 XStream 就能直接序列化/逆序列化任何第三方類。
設(shè)置開發(fā)環(huán)境
按照下列步驟下載和安裝 XStream(下載鏈接參見 參考資料):
1. 從 Eclipse 網(wǎng)站下載 Eclipse。安裝的時候?qū)⑵浣鈮旱竭x定的文件夾,本文中用 eclipse_home 表示。本文假定使用 Eclipse 3.3。
2. 從 XStream 網(wǎng)站下載最新的 XStream 穩(wěn)定版本。安裝的時候解壓到選定的文件夾,本文用 xstream_home 表示。假定使用的 XStream 版本是 1.2.2。
3. 從 Sun 網(wǎng)站下載 Java Platform, Standard Edition (J2SE) 軟件開發(fā)工具箱(SDK)。安裝到選定的文件夾,本文用 java_home 表示。假定版本為 1.5.0_05。
創(chuàng)建一個 Java 項目
要創(chuàng)建一個 Java 項目,需要選擇 File > New > Project,然后按下列步驟操作:
1. 選擇 Java > Java Project > Next(如圖 1 所示)。
2. 填寫項目名稱并單擊 Next(如 圖 2 所示)。
3. 單擊 Finish 完成該任務(wù)(如 圖 3 所示)。
#p#
圖 4 顯示了新建的 Java 項目。
添加 XStream 支持
按照下列步驟向新建的項目添加 XStream 庫:
1. 在 Eclipse 的 Project Explorer 中選擇新建的項目,從 Project 菜單中選擇 Properties(如 圖 5 所示)。
2. 單擊 Add External JARs,從 xstream_home/lib 文件夾中選擇 xstream-1.2.2.jar。
3. 單擊 OK 結(jié)束(如 圖 6 所示)。
圖 7 顯示了添加 XStream 支持后的項目。
序列化對象
這個簡單的例子示范了如何使用 XStream 序列化/逆序列化對象,包括兩個類:Writer 和 Reader。Writer 類使用 XStream API 把 Employee 類型的對象序列化為 XML 并存儲到文件中(如 清單 1 所示)。
清單 1. Writer.java
package com.samples; 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(); //Set the properties using the setter methods //Note: This can also be done with a constructor. //Since we want to show that XStream can serialize //even without a constructor, this approach is used. e.setName("Jack"); e.setDesignation("Manager"); e.setDepartment("Finance"); //Serialize the object XStream xs = new XStream(); //Write to a file in the file system try { FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt"); xs.toXML(e, fs); } catch (FileNotFoundException e1) { e1.printStackTrace(); } } }
Reader 類讀取該文件,逆序列化 XML 并把數(shù)據(jù)裝入 Java 對象(如 清單 2 所示)。
#p#
清單 2. Reader.java
package com.samples;
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);
//print the data from the object that has been read
System.out.println(e.toString());
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
清單 3 顯示了 Employee 對象的結(jié)構(gòu)。
package com.samples;
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;
}
}
讀取配置文件
多數(shù)應(yīng)用程序都要用到一些屬性。這些屬性可能是要連接的數(shù)據(jù)源的名稱或者日志文件的位置。配置文件最適合存儲這類數(shù)據(jù),從而在修改這些屬性的時候不需要重新編譯應(yīng)用程序,應(yīng)用程序維護起來也更容易。下面的例子說明如何在應(yīng)用程序中使用 XStream 從 XML 配置文件中讀取配置屬性。
XML 數(shù)據(jù)綁定通常需要從 XML 文件生成 Java 對象。使用 XStream 省略了生成對象這個步驟。只需要編寫一個 Java 類將類的字段映射到希望讀取的 XML 的元素。這個例子使用的配置文件如 清單 4 所示。
清單 4. Config.xml
<?xml version="1.0" encoding="UTF-8"?> <config> <datasource-name>IRIS</datasource-name> <ipaddress>9.124.74.85</ipaddress> <logfilename>DailyLogApplication.log</logfilename> <appender>console</appender> </config> |
清單 5 顯示的 ConfigReader 類讀取該配置文件并將屬性加載到 Java 對象中。
清單 5. ConfigReader.java
package com.samples;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class ConfigReader {
String datasourcename = null;
String ipaddress = null;
String logfilename = null;
String appender = null;
@Override
public String toString() {
// This method prints out the values stored in the member variables
return "Datasource Name : "+datasourcename+
" \nIP Address : "+ipaddress+
" \nLogfilename : "+logfilename+
" \nAppender : "+appender;
}
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
XStream xs = new XStream(new DomDriver());
FileInputStream fis = new FileInputStream("c:/temp/Config.xml");
xs.aliasField("datasource-name", ConfigReader.class, "datasourcename");
xs.alias("config", ConfigReader.class);
ConfigReader r = (ConfigReader)xs.fromXML(fis);
System.out.println(r.toString());
}
}
結(jié)束語
創(chuàng)建和開發(fā)使用 XStream 的應(yīng)用程序只需要簡單的幾個步驟。本文介紹如何使用 XStream 序列化/逆序列化 Java 對象和讀取配置文件,通過 XStream 網(wǎng)站(教程鏈接參見 參考資料)可以進一步了解別名、注解和轉(zhuǎn)換程序。別名和轉(zhuǎn)換程序可以讓您完全控制生成的 XML。
【編輯推薦】