最近寫(xiě)一個(gè)題目,要求將一組員工實(shí)體類(lèi)轉(zhuǎn)換成xml文件,或?qū)ml文件轉(zhuǎn)換成一組實(shí)體類(lèi)。題目不難,但寫(xiě)完感覺(jué)可以利用泛型和反射將任意一個(gè)實(shí)體類(lèi)和xml文件進(jìn)行轉(zhuǎn)換。于是今天下午立馬動(dòng)手
試了下,做了個(gè)簡(jiǎn)單的模型,可以將簡(jiǎn)單的實(shí)體類(lèi)和xml文件進(jìn)行相互轉(zhuǎn)換,但對(duì)實(shí)體類(lèi)的屬性類(lèi)型有限制,目前只支持String, Integer, Double三種類(lèi)型。但是后面可以擴(kuò)展。
我的大概思路是這樣的,只要能拿到實(shí)體類(lèi)的類(lèi)型信息,我就能拿到實(shí)體類(lèi)的全部字段名稱(chēng)和類(lèi)型,拼屬性的set和get方法更是簡(jiǎn)單明了,這時(shí)候只需要通過(guò)方法的反射,將xml文件的數(shù)據(jù)讀取出來(lái)給這個(gè)反射即可。
反過(guò)來(lái)只要給我一個(gè)任意對(duì)象,我就能通過(guò)反射拿到該對(duì)象所有字段的值,這時(shí)候在寫(xiě)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(); /** * 判斷是否是個(gè)xml文件,目前類(lèi)里尚未使用該方法 * @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; } /** * 將一組對(duì)象數(shù)據(jù)轉(zhuǎn)換成XML文件 * @param list * @param filePath 存放的文件路徑 */ public static <T> void writeXML(List<T> 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(); } } } /** * 通過(guò)一個(gè)根節(jié)點(diǎn)來(lái)寫(xiě)對(duì)象的xml節(jié)點(diǎn),這個(gè)方法不對(duì)外開(kāi)放,主要給writeXML(List<T> list, String filePath)提供服務(wù) * @param root * @param object * @return * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ private static Element writeXml(Element root, Object object) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> c = object.getClass(); String className = c.getSimpleName().toLowerCase(); Element ele = root.addElement(className); Field[] fields = c.getDeclaredFields(); for(Field f : fields) { String fieldName = f.getName(); String param = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Element fieldElement = ele.addElement(fieldName); Method m = c.getMethod("get" + param, null); String s = ""; if(m.invoke(object, null) != null) { s = m.invoke(object, null).toString(); } fieldElement.setText(s); } return root; } /** * 默認(rèn)使用utf-8 * @param c * @param filePath * @return * @throws UnsupportedEncodingException * @throws FileNotFoundException */ public static <T> List<T> getEntitys(Class<T> c, String filePath) throws UnsupportedEncodingException, FileNotFoundException { return getEntitys(c, filePath, "utf-8"); } /** * 將一個(gè)xml文件轉(zhuǎn)變成實(shí)體類(lèi) * @param c * @param filePath * @return * @throws FileNotFoundException * @throws UnsupportedEncodingException */ public static <T> List<T> getEntitys(Class<T> c, String filePath, String encoding) throws UnsupportedEncodingException, FileNotFoundException { File file = new File(filePath); String labelName = c.getSimpleName().toLowerCase(); SAXReader reader = new SAXReader(); List<T> list = null; try { InputStreamReader in = new InputStreamReader(new FileInputStream(file), encoding); Document document = reader.read(in); Element root = document.getRootElement(); List elements = root.elements(labelName); list = new ArrayList<T>(); for(Iterator<Emp> it = elements.iterator(); it.hasNext();) { Element e = (Element)it.next(); T t = getEntity(c, e); list.add(t); } } catch (DocumentException e) { e.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (NoSuchMethodException e1) { e1.printStackTrace(); } catch (SecurityException e1) { e1.printStackTrace(); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (InvocationTargetException e1) { e1.printStackTrace(); } return list; } /** * 將一種類(lèi)型 和對(duì)應(yīng)的 xml元素節(jié)點(diǎn)傳進(jìn)來(lái),返回該類(lèi)型的對(duì)象,該方法不對(duì)外開(kāi)放 * @param c 類(lèi)類(lèi)型 * @param ele 元素節(jié)點(diǎn) * @return 該類(lèi)型的對(duì)象 * @throws InstantiationException * @throws IllegalAccessException * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalArgumentException * @throws InvocationTargetException */ @SuppressWarnings("unchecked") private static <T> T getEntity(Class<T> c, Element ele) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Field[] fields = c.getDeclaredFields(); Object object = c.newInstance();// for(Field f : fields) { String type = f.getType().toString();//獲得字段的類(lèi)型 String fieldName = f.getName();//獲得字段名稱(chēng) String param = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);//把字段的第一個(gè)字母變成大寫(xiě) Element e = ele.element(fieldName); if(type.indexOf("Integer") > -1) {//說(shuō)明該字段是Integer類(lèi)型 Integer i = null; if(e.getTextTrim() != null && !e.getTextTrim().equals("")) { i = Integer.parseInt(e.getTextTrim()); } Method m = c.getMethod("set" + param, Integer.class); m.invoke(object, i);//通過(guò)反射給該字段set值 } if(type.indexOf("Double") > -1) { //說(shuō)明該字段是Double類(lèi)型 Double d = null; if(e.getTextTrim() != null && !e.getTextTrim().equals("")) { d = Double.parseDouble(e.getTextTrim()); } Method m = c.getMethod("set" + param, Double.class); m.invoke(object, d); } if(type.indexOf("String") > -1) {//說(shuō)明該字段是String類(lèi)型 String s = null; if(e.getTextTrim() != null && !e.getTextTrim().equals("")) { s = e.getTextTrim(); } Method m = c.getMethod("set" + param, String.class); m.invoke(object, s); } } return (T)object; } /** * 用來(lái)寫(xiě)xml文件 * @param doc Document對(duì)象 * @param filePath 生成的文件路徑 * @param encoding 寫(xiě)xml文件的編碼 */ public static void writeXml(Document doc, String filePath, String encoding) { XMLWriter writer = null; OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding);// 指定XML編碼 try { writer = new XMLWriter(new FileWriter(filePath), format); writer.write(doc); } catch (IOException e) { e.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 默認(rèn)使用utf-8的格式寫(xiě)文件 * @param doc * @param filePath */ public static void writeXml(Document doc, String filePath) { writeXml(doc, filePath, "utf-8"); } }
假如有個(gè)實(shí)體類(lèi)是:
package com.pcq.entity; import java.io.Serializable; public class Emp implements Serializable{ private Integer id; private String name; private Integer deptNo; private Integer age; private String gender; private Integer bossId; private Double salary; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getDeptNo() { return deptNo; } public void setDeptNo(Integer deptNo) { this.deptNo = deptNo; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Integer getBossId() { return bossId; } public void setBossId(Integer bossId) { this.bossId = bossId; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } }
那么寫(xiě)出來(lái)的xml文件格式如下:
<?xml version="1.0" encoding="utf-8"?> <emps> <emp> <id>1</id> <name>張三</name> <deptNo>50</deptNo> <age>25</age> <gender>男</gender> <bossId>6</bossId> <salary>9000.0</salary> </emp> <emp> <id>2</id> <name>李四</name> <deptNo>50</deptNo> <age>22</age> <gender>女</gender> <bossId>6</bossId> <salary>8000.0</salary> </emp> </emps>
假如有個(gè)實(shí)體類(lèi)如下:
package com.pcq.entity; public class Student { private Integer id; private String name; private Integer age; private String gender; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
那么寫(xiě)出來(lái)的xml文件如下
<?xml version="1.0" encoding="utf-8"?> <students> <student> <id></id> <name>pcq</name> <age>18</age> <gender>男</gender> </student> </students>
讀取也必須讀這種格式的xml文件,才能轉(zhuǎn)換成實(shí)體類(lèi),要求是實(shí)體類(lèi)的類(lèi)類(lèi)型信息(Class)必須要獲得到。
另外這里的實(shí)體類(lèi)的屬性類(lèi)型均是Integer,String,Double,可以看到工具類(lèi)里只對(duì)這三種類(lèi)型做了判斷。而且可以預(yù)想的是,如果出現(xiàn)一對(duì)多的關(guān)系,即一個(gè)實(shí)體類(lèi)擁有一組另一個(gè)類(lèi)對(duì)象的引用,
那xml和實(shí)體類(lèi)的相互轉(zhuǎn)換要比上述的情況復(fù)雜的多。lz表示短時(shí)間內(nèi)甚至長(zhǎng)時(shí)間內(nèi)也不一定能做的出來(lái),歡迎同道高人指點(diǎn)。
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請(qǐng)關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
AJAX如何檢測(cè)用戶(hù)名是否具有重復(fù)性
用Ajax如何驗(yàn)證郵箱、用戶(hù)名的唯一性
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com