使用反射机制恢复xml文件表示的对象

前端之家收集整理的这篇文章主要介绍了使用反射机制恢复xml文件表示的对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

题目:

完成如下功能
1)有一个(任意)对象,里面有N个properties以及getter和setter方法
2)有一个properties文件,有N个key,value来描述对象中property的值
3)有一个scheme固定的xml,用来描述这个对象


要求写一个解析器:
1)将xml中的占位符,替换为properties文件中的value
2) 将xml解析成对象,调用getter方法的时候可以获得值
3)用面向对象的思想,使该解析器有扩展性


例子见附件,注意:
1)对象是任意对象,不是例子中的Student,对象中的property都是java中的原生类型
2)xml和properties在使用的时候都是根据对象配置好的
3) xml的scheme是固定的,就是附件中的scheme


Student.java文件

  1. import java.util.Date;
  2.  
  3. /**
  4. * Created by IntelliJ IDEA.
  5. * User: liuzz
  6. * Date: 13-11-2
  7. * Time: 下午11:53
  8. */
  9. public class Student {
  10.  
  11. private String name;
  12.  
  13. private int age;
  14.  
  15. private Date birth;
  16.  
  17. public String getName() {
  18. return name;
  19. }
  20.  
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24.  
  25. public int getAge() {
  26. return age;
  27. }
  28.  
  29. public void setAge(int age) {
  30. this.age = age;
  31. }
  32.  
  33. public Date getBirth() {
  34. return birth;
  35. }
  36.  
  37. public void setBirth(Date birth) {
  38. this.birth = birth;
  39. }
  40. public String toString(){
  41. return "[ name = " + name +",age = "+age+",birth = " + birth+"]";
  42. }
  43. }

object.properties2文件
  1. name=a
  2. age=10
  3. birth=2003-11-04


object.xml文件
  1. <object class="MyTest.MyTest.Week2.Student">
  2. <property name="name">
  3. <value>${name}</value>
  4. </property>
  5. <property name="age">
  6. <value>${age}</value>
  7. </property>
  8. <property name="birth">
  9. <value>${birth}</value>
  10. </property>
  11. </object>



代码实现:
  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.lang.reflect.AnnotatedType;
  8. import java.lang.reflect.Field;
  9. import java.sql.Date;
  10. import java.text.ParseException;
  11. import java.text.SimpleDateFormat;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. import java.util.Properties;
  15. import java.util.Scanner;
  16.  
  17. import javax.xml.parsers.DocumentBuilder;
  18. import javax.xml.parsers.DocumentBuilderFactory;
  19. import javax.xml.parsers.ParserConfigurationException;
  20.  
  21. import org.jdom.Document;
  22. import org.jdom.Element;
  23. import org.jdom.JDOMException;
  24. import org.jdom.input.SAXBuilder;
  25. import org.w3c.dom.Node;
  26. import org.w3c.dom.NodeList;
  27. import org.xml.sax.SAXException;
  28.  
  29. import com.google.common.io.Files;
  30.  
  31. public class RecoverObject<O> {
  32. private String propertiesFile;
  33. private String objectXmlFile;
  34. private String recoverObjextXmlFile;
  35. private String clazzName;
  36. private Properties properties;
  37. public RecoverObject(String propertiesFile,String objectXmlFile){
  38. this.propertiesFile = propertiesFile;
  39. this.objectXmlFile = objectXmlFile;
  40. this.recoverObjextXmlFile = this.objectXmlFile+".recover";
  41. this.properties = new Properties();
  42. initObject();
  43. }
  44. private void processXmlFile(String context){
  45. int pre = -1,s = -1,e = -1;
  46. StringBuffer buffer = new StringBuffer();
  47. while((s = context.indexOf("${",pre+1))!=-1){
  48. e = context.indexOf("}",s + 2);
  49. buffer.append(context.substring(pre+1,s));
  50. String attr = context.substring(s+2,e);
  51. buffer.append(this.properties.get(attr));
  52. pre = e;
  53. }
  54. buffer.append(context.substring(pre+1));
  55. try {
  56. Files.write(buffer.toString().getBytes(),new File(this.recoverObjextXmlFile));
  57. } catch (IOException e1) {
  58. // TODO Auto-generated catch block
  59. e1.printStackTrace();
  60. }
  61. }
  62. private void initObject(){
  63. FileInputStream in;
  64. try {
  65. in = new FileInputStream(new File(this.propertiesFile));
  66. this.properties.load(in);
  67. in.close();
  68. } catch (FileNotFoundException e) {
  69. e.printStackTrace();
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. StringBuffer buffer = new StringBuffer();
  74. try {
  75. Scanner scan = new Scanner(new FileInputStream(new File(this.objectXmlFile)));
  76. while(scan.hasNextLine()){
  77. buffer.append(scan.nextLine());
  78. buffer.append("\n");
  79. }
  80. } catch (FileNotFoundException e) {
  81. // TODO Auto-generated catch block
  82. e.printStackTrace();
  83. }
  84. String context = buffer.toString();
  85. this.processXmlFile(context);
  86. }
  87. public O get(){
  88. SAXBuilder builder=new SAXBuilder(false);
  89. Class<?> demo=null;
  90. try {
  91. Document doc=builder.build(this.recoverObjextXmlFile);
  92. Element object=doc.getRootElement();
  93. this.clazzName = object.getAttributeValue("class");
  94. demo=Class.forName(this.clazzName);
  95. O o = (O) demo.newInstance();
  96. List propertiesList = object.getChildren("property");
  97. for(Iterator iter = propertiesList.iterator(); iter.hasNext();){
  98. Element attr = (Element) iter.next();
  99. String attrName = attr.getAttributeValue("name");
  100. String attrValue = attr.getChildText("value");
  101. Field f= demo.getDeclaredField(attrName);
  102. f.setAccessible(true);
  103. Class<?> type = f.getType();
  104. if(type.equals(String.class)){
  105. f.set(o,attrValue);
  106. }else if(type.equals(int.class)){
  107. f.set(o,Integer.parseInt(attrValue));
  108. }else if(type.equals(java.util.Date.class)){
  109. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  110. f.set(o,format.parse(attrValue));
  111. }
  112. }
  113. return o;
  114. } catch (JDOMException e) {
  115. e.printStackTrace();
  116. } catch (IOException e) {
  117. e.printStackTrace();
  118. } catch (ClassNotFoundException e) {
  119. // TODO Auto-generated catch block
  120. e.printStackTrace();
  121. } catch (InstantiationException e) {
  122. // TODO Auto-generated catch block
  123. e.printStackTrace();
  124. } catch (IllegalAccessException e) {
  125. // TODO Auto-generated catch block
  126. e.printStackTrace();
  127. } catch (NoSuchFieldException e) {
  128. // TODO Auto-generated catch block
  129. e.printStackTrace();
  130. } catch (SecurityException e) {
  131. // TODO Auto-generated catch block
  132. e.printStackTrace();
  133. } catch (IllegalArgumentException e) {
  134. // TODO Auto-generated catch block
  135. e.printStackTrace();
  136. } catch (ParseException e) {
  137. // TODO Auto-generated catch block
  138. e.printStackTrace();
  139. }
  140. return null;
  141. }
  142. public static void main(String [] args){
  143. RecoverObject<Student> object = new RecoverObject<Student>("./source/object.properties2","./source/object.xml");
  144. Student s = object.get();
  145. System.out.println(s);
  146. }
  147. }

猜你在找的XML相关文章