最近写一个题目,要求将一组员工实体类转换成xml文件,或将xml文件转换成一组实体类。题目不难,但写完感觉可以利用泛型和反射将任意一个实体类和xml文件进行转换。于是今天下午立马动手
试了下,做了个简单的模型,可以将简单的实体类和xml文件进行相互转换,但对实体类的属性类型有限制,目前只支持String, Integer, Double三种类型。但是后面可以扩展。
我的大概思路是这样的,只要能拿到实体类的类型信息,我就能拿到实体类的全部字段名称和类型,拼属性的set和get方法更是简单明了,这时候只需要通过方法的反射,将xml文件的数据读取出来给这个反射即可。
反过来只要给我一个任意对象,我就能通过反射拿到该对象所有字段的值,这时候在写xml文件即可。
具体代码如下:
package com.pcq.entity;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XMLAndEntityUtil {
private static Document document = DocumentHelper.createDocument();
/**
* 判断是否是个xml文件,目前类里尚未使用该方法
* @param filePath
* @return
*/
@SuppressWarnings("unused")
private static boolean isXMLFile(String filePath) {
File file = new File(filePath);
if(!file.exists() || filePath.indexOf(".xml") > -1) {
return false;
}
return true;
}
/**
* 将一组对象数据转换成XML文件
* @param list
* @param filePath 存放的文件路径
*/
public static void writeXML(List list, String filePath) {
Class> c = list.get(0).getClass();
String root = c.getSimpleName().toLowerCase() + "s";
Element rootEle = document.addElement(root);
for(Object obj : list) {
try {
Element e = writeXml(rootEle, obj);
document.setRootElement(e);
writeXml(document, filePath);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
}
/**
* 通过一个根节点来写对象的xml节点&#x