今天看了下JAVA序列化。还是一知半解。怎么也没有弄明白,怎么序列化成XML文件。处入半解状态。在网上找了很多,大部分是理论上的。没有实际的例子。功夫不负有心人,终于找到了。做了下测试终于成功。忍不住记录的下来。
JXmlSerializable 是一个利用java反射,通过调用对象中所有以get(不区分大小写)开头的方法除去getClass方法,生成xml格式,希望与大家分享一下
下面是一个parent对象,包含两个child对象 生成的xml如下
Child类
package xmlTest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
public class Child extends JXmlSerializable {
private String _name;
private String _sex;
private int age;
public void setAge(int num) {
age = num;
}
public int getAge() {
return age;
}
public void setName(String name) {
_name = name;
}
public void setSex(String sex) {
_sex = sex;
}
public String getName() {
return _name;
}
public String getSex() {
return _sex;
}
}
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
public class Child extends JXmlSerializable {
private String _name;
private String _sex;
private int age;
public void setAge(int num) {
age = num;
}
public int getAge() {
return age;
}
public void setName(String name) {
_name = name;
}
public void setSex(String sex) {
_sex = sex;
}
public String getName() {
return _name;
}
public String getSex() {
return _sex;
}
}
Parent类
package xmlTest;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
public class Parent extends JXmlSerializable {
private String _name;
private String _sex;
private LinkedList list = new LinkedList();
private Vector vec = new Vector();
int age;
public void setAge(int num) {
age = num;
}
public int getAge() {
return age;
}
public void setName(String name) {
_name = name;
}
public void setSex(String sex) {
_sex = sex;
}
public String getName() {
return _name;
}
public String getSex() {
return _sex;
}
public void addChild(Child child) {
list.add(child);
vec.add(child);
}
public Child[] getChild() {
Child[] aa = new Child[vec.size()];
// list.toArray(aa);
vec.toArray(aa);
return aa;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Parent pat = new Parent();
pat.setName("jack");
pat.setSex("male");
Child child1 = new Child();
child1.setName("tom");
child1.setSex("male");
pat.addChild(child1);
Child child2 = new Child();
child2.setName("Marie");
child2.setSex("female");
pat.addChild(child2);
pat.getChild();
PrintWriter out = new PrintWriter("abc.xml");
pat.toXmlSerial(out,0);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
public class Parent extends JXmlSerializable {
private String _name;
private String _sex;
private LinkedList list = new LinkedList();
private Vector vec = new Vector();
int age;
public void setAge(int num) {
age = num;
}
public int getAge() {
return age;
}
public void setName(String name) {
_name = name;
}
public void setSex(String sex) {
_sex = sex;
}
public String getName() {
return _name;
}
public String getSex() {
return _sex;
}
public void addChild(Child child) {
list.add(child);
vec.add(child);
}
public Child[] getChild() {
Child[] aa = new Child[vec.size()];
// list.toArray(aa);
vec.toArray(aa);
return aa;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Parent pat = new Parent();
pat.setName("jack");
pat.setSex("male");
Child child1 = new Child();
child1.setName("tom");
child1.setSex("male");
pat.addChild(child1);
Child child2 = new Child();
child2.setName("Marie");
child2.setSex("female");
pat.addChild(child2);
pat.getChild();
PrintWriter out = new PrintWriter("abc.xml");
pat.toXmlSerial(out,0);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
类 JXmlSerializable
package xmlTest;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Array;
import java.io.PrintWriter;
import java.io.IOException;
public class JXmlSerializable {
public void toXmlSerial(PrintWriter out, int num)
throws InvocationTargetException, IllegalAccessException,
IOException {
out.write("<?xml version="1.0"?> ");
String head = "";
for (int i = 0; i < num; i++) {
head += " ";
}
out.write(head + "<" + this.getClass().getName() + "> ");
Method[] methods = this.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Class[] paras = methods[i].getParameterTypes();
String name = methods[i].getName();
if (paras == null || paras.length == 0) {
if ((name.substring(0, 3).toLowerCase().equals("get"))
&& !name.equals("getClass")) {
Object obj = methods[i].invoke(this, null);
getMethodXmlSerial(out, obj, methods[i], num);
}
}
}
out.write(head + "</" + this.getClass().getName() + "> ");
}
private void getMethodXmlSerial(PrintWriter out, Object obj, Method method,
int num) throws InvocationTargetException, IllegalAccessException,
IOException {
if (obj == null)
return;
String head = "";
for (int i = 0; i <= num; i++) {
head += " ";
}
if (obj.getClass().isArray()) {
for (int i = 0; i < Array.getLength(obj); i++) {
Object childobj = Array.get(obj, i);
if (childobj instanceof JXmlSerializable) {
((JXmlSerializable) childobj).toXmlSerial(out, num + 1);
} else {
getMethodXmlSerial(out, childobj, method, num);
}
}
} else {
out.write(head + " <" + method.getName().substring(3) + "> ");
out.write(obj.toString());
out.write(" </" + method.getName().substring(3) + "> ");
}
}
}
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Array;
import java.io.PrintWriter;
import java.io.IOException;
public class JXmlSerializable {
public void toXmlSerial(PrintWriter out, int num)
throws InvocationTargetException, IllegalAccessException,
IOException {
out.write("<?xml version="1.0"?> ");
String head = "";
for (int i = 0; i < num; i++) {
head += " ";
}
out.write(head + "<" + this.getClass().getName() + "> ");
Method[] methods = this.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Class[] paras = methods[i].getParameterTypes();
String name = methods[i].getName();
if (paras == null || paras.length == 0) {
if ((name.substring(0, 3).toLowerCase().equals("get"))
&& !name.equals("getClass")) {
Object obj = methods[i].invoke(this, null);
getMethodXmlSerial(out, obj, methods[i], num);
}
}
}
out.write(head + "</" + this.getClass().getName() + "> ");
}
private void getMethodXmlSerial(PrintWriter out, Object obj, Method method,
int num) throws InvocationTargetException, IllegalAccessException,
IOException {
if (obj == null)
return;
String head = "";
for (int i = 0; i <= num; i++) {
head += " ";
}
if (obj.getClass().isArray()) {
for (int i = 0; i < Array.getLength(obj); i++) {
Object childobj = Array.get(obj, i);
if (childobj instanceof JXmlSerializable) {
((JXmlSerializable) childobj).toXmlSerial(out, num + 1);
} else {
getMethodXmlSerial(out, childobj, method, num);
}
}
} else {
out.write(head + " <" + method.getName().substring(3) + "> ");
out.write(obj.toString());
out.write(" </" + method.getName().substring(3) + "> ");
}
}
}
编译出来还可以,能够达到我的理想。
编译结果是
<?xml version="1.0"?>
<xmlTest.Parent>
<Name> jack </Name>
<Age> 0 </Age>
<Sex> male </Sex>
<?xml version="1.0"?>
<xmlTest.Child>
<Name> tom </Name>
<Age> 0 </Age>
<Sex> male </Sex>
</xmlTest.Child>
<?xml version="1.0"?>
<xmlTest.Child>
<Name> Marie </Name>
<Age> 0 </Age>
<Sex> female </Sex>
</xmlTest.Child>
</xmlTest.Parent>
<xmlTest.Parent>
<Name> jack </Name>
<Age> 0 </Age>
<Sex> male </Sex>
<?xml version="1.0"?>
<xmlTest.Child>
<Name> tom </Name>
<Age> 0 </Age>
<Sex> male </Sex>
</xmlTest.Child>
<?xml version="1.0"?>
<xmlTest.Child>
<Name> Marie </Name>
<Age> 0 </Age>
<Sex> female </Sex>
</xmlTest.Child>
</xmlTest.Parent>
谢谢like199的分享。
今天看了看java.beans包,发现了两个好东西,XMLEncoder和XMLDecoder。发现自己以前把从XML存取对象真是太费力气啦。做了小工具类,以后可以用用了。
以下是引用片段: package com.imct.util; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * <title>使用XML文件存取可序列化的对象的类</title> * <description>提供保存和读取的方法</description> * @author 殷晋 * <copyright>清华大学汽车工程开发研究院@2005</copyright> * @version 1.0 * 2005-8-5 16:44:49 */ public class ObjectToXMLUtil { /** * 把java的可序列化的对象(实现Serializable接口)序列化保存到XML文件里面,如果想一次保存多个可序列化对象请用集合进行封装 * 保存时将会用现在的对象原来的XML文件内容 * @param obj 要序列化的可序列化的对象 * @param fileName 带完全的保存路径的文件名 * @throws FileNotFoundException 指定位置的文件不存在 * @throws IOException 输出时发生异常 * @throws Exception 其他运行时异常 */ public static void objectXmlEncoder(Object obj,String fileName) throws FileNotFoundException,IOException,Exception { //创建输出文件 File fo = new File(fileName); //文件不存在,就创建该文件 if(!fo.exists()) { //先创建文件的目录 String path = fileName.substring(0,fileName.lastIndexOf('.')); File pFile = new File(path); pFile.mkdirs(); } //创建文件输出流 FileOutputStream fos = new FileOutputStream(fo); //创建XML文件对象输出类实例 XMLEncoder encoder = new XMLEncoder(fos); //对象序列化输出到XML文件 encoder.writeObject(obj); encoder.flush(); //关闭序列化工具 encoder.close(); //关闭输出流 fos.close(); } /** * 读取由objSource指定的XML文件中的序列化保存的对象,返回的结果经过了List封装 * @param objSource 带全部文件路径的文件全名 * @return 由XML文件里面保存的对象构成的List列表(可能是一个或者多个的序列化保存的对象) * @throws FileNotFoundException 指定的对象读取资源不存在 * @throws IOException 读取发生错误 * @throws Exception 其他运行时异常发生 */ public static List objectXmlDecoder(String objSource) throws FileNotFoundException,IOException,Exception { List objList = new ArrayList(); File fin = new File(objSource); FileInputStream fis = new FileInputStream(fin); XMLDecoder decoder = new XMLDecoder(fis); Object obj = null; try { while( (obj = decoder.readObject()) != null) { objList.add(obj); } } catch (Exception e) { // TODO Auto-generated catch block } fis.close(); decoder.close(); return objList; } } |
当然用Beans.instantiate也可以从文件中反序列化初对象