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

本文介绍了一种用于从XML文件和Properties文件中解析并重建Java对象的方法。该解析器可以处理任意Java对象,通过替换XML文件中的占位符为Properties文件中的值,并将XML描述转换为实际的对象实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

完成如下功能:
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

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: liuzz
 * Date: 13-11-2
 * Time: 下午11:53
 */
public class Student {

    private String name;

    private int age;

    private Date birth;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public String toString(){
        return "[ name = " + name +" , age = "+age+" , birth = " + birth+"]";
    }
}

object.properties2文件

name=a  
age=10  
birth=2003-11-04 

object.xml文件

<object class="MyTest.MyTest.Week2.Student">  
    <property name="name">  
        <value>${name}</value>  
    </property>  
    <property name="age">  
        <value>${age}</value>  
    </property>  
    <property name="birth">  
        <value>${birth}</value>  
    </property>  
</object>  

代码实现:

import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  
import java.lang.reflect.AnnotatedType;  
import java.lang.reflect.Field;  
import java.sql.Date;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Properties;  
import java.util.Scanner;  
  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import javax.xml.parsers.ParserConfigurationException;  
  
import org.jdom.Document;  
import org.jdom.Element;  
import org.jdom.JDOMException;  
import org.jdom.input.SAXBuilder;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
import org.xml.sax.SAXException;  
  
import com.google.common.io.Files;  
  
public class RecoverObject<O> {  
    private String propertiesFile;  
    private String objectXmlFile;  
    private String recoverObjextXmlFile;  
    private String clazzName;  
    private Properties properties;  
    public RecoverObject(String propertiesFile, String objectXmlFile){  
        this.propertiesFile = propertiesFile;  
        this.objectXmlFile = objectXmlFile;  
        this.recoverObjextXmlFile = this.objectXmlFile+".recover";  
          
        this.properties = new Properties();  
        initObject();  
    }  
    private void processXmlFile(String context){  
        int pre = -1, s = -1, e = -1;  
        StringBuffer buffer = new StringBuffer();  
        while((s = context.indexOf("${", pre+1))!=-1){  
            e = context.indexOf("}", s + 2);  
            buffer.append(context.substring(pre+1, s));  
            String attr = context.substring(s+2, e);  
            buffer.append(this.properties.get(attr));  
            pre = e;  
        }  
        buffer.append(context.substring(pre+1));  
        try {  
            Files.write(buffer.toString().getBytes(), new File(this.recoverObjextXmlFile));  
        } catch (IOException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }  
          
    }  
    private void initObject(){  
        FileInputStream in;  
        try {  
            in = new FileInputStream(new File(this.propertiesFile));  
            this.properties.load(in);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }   
        StringBuffer buffer = new StringBuffer();  
        try {  
            Scanner scan = new Scanner(new FileInputStream(new File(this.objectXmlFile)));  
            while(scan.hasNextLine()){  
                buffer.append(scan.nextLine());  
                buffer.append("\n");  
            }  
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        String context = buffer.toString();  
        this.processXmlFile(context);  
          
    }  
      
    public O get(){  
        SAXBuilder builder=new SAXBuilder(false);  
        Class<?> demo=null;  
        try {  
            Document doc=builder.build(this.recoverObjextXmlFile);  
            Element object=doc.getRootElement();  
            this.clazzName = object.getAttributeValue("class");  
            demo=Class.forName(this.clazzName);  
            O o = (O) demo.newInstance();  
            List propertiesList = object.getChildren("property");  
            for(Iterator iter = propertiesList.iterator(); iter.hasNext();){  
                Element attr = (Element) iter.next();  
                String attrName = attr.getAttributeValue("name");  
                String attrValue = attr.getChildText("value");  
                Field f= demo.getDeclaredField(attrName);  
                f.setAccessible(true);  
                Class<?> type = f.getType();  
                if(type.equals(String.class)){  
                    f.set(o, attrValue);  
                }else if(type.equals(int.class)){  
                    f.set(o, Integer.parseInt(attrValue));  
                }else if(type.equals(java.util.Date.class)){  
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
                    f.set(o, format.parse(attrValue));  
                }  
                  
            }  
            return o;  
        } catch (JDOMException e) {  
              
            e.printStackTrace();  
        } catch (IOException e) {  
              
            e.printStackTrace();  
        } catch (ClassNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (InstantiationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IllegalAccessException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (NoSuchFieldException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SecurityException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IllegalArgumentException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (ParseException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
          
        return null;  
    }  
    public static void main(String [] args){  
        RecoverObject<Student> object = new RecoverObject<Student>("./source/object.properties2", "./source/object.xml");  
        Student s = object.get();  
        System.out.println(s);  
    }  
} 

 

完成如下功能:
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文件

 

[java]  view plain  copy
 
  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文件

 

 

[plain]  view plain  copy
 
  1. name=a  
  2. age=10  
  3. birth=2003-11-04  

 

 

object.xml文件

 

[html]  view plain  copy
 
  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>  

 

 

 

代码实现:

 

[java]  view plain  copy
 
  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.           
  42.         this.properties = new Properties();  
  43.         initObject();  
  44.     }  
  45.     private void processXmlFile(String context){  
  46.         int pre = -1, s = -1, e = -1;  
  47.         StringBuffer buffer = new StringBuffer();  
  48.         while((s = context.indexOf("${", pre+1))!=-1){  
  49.             e = context.indexOf("}", s + 2);  
  50.             buffer.append(context.substring(pre+1, s));  
  51.             String attr = context.substring(s+2, e);  
  52.             buffer.append(this.properties.get(attr));  
  53.             pre = e;  
  54.         }  
  55.         buffer.append(context.substring(pre+1));  
  56.         try {  
  57.             Files.write(buffer.toString().getBytes(), new File(this.recoverObjextXmlFile));  
  58.         } catch (IOException e1) {  
  59.             // TODO Auto-generated catch block  
  60.             e1.printStackTrace();  
  61.         }  
  62.           
  63.     }  
  64.     private void initObject(){  
  65.         FileInputStream in;  
  66.         try {  
  67.             in = new FileInputStream(new File(this.propertiesFile));  
  68.             this.properties.load(in);  
  69.             in.close();  
  70.         } catch (FileNotFoundException e) {  
  71.             e.printStackTrace();  
  72.         } catch (IOException e) {  
  73.             e.printStackTrace();  
  74.         }   
  75.         StringBuffer buffer = new StringBuffer();  
  76.         try {  
  77.             Scanner scan = new Scanner(new FileInputStream(new File(this.objectXmlFile)));  
  78.             while(scan.hasNextLine()){  
  79.                 buffer.append(scan.nextLine());  
  80.                 buffer.append("\n");  
  81.             }  
  82.         } catch (FileNotFoundException e) {  
  83.             // TODO Auto-generated catch block  
  84.             e.printStackTrace();  
  85.         }  
  86.         String context = buffer.toString();  
  87.         this.processXmlFile(context);  
  88.           
  89.     }  
  90.       
  91.     public O get(){  
  92.         SAXBuilder builder=new SAXBuilder(false);  
  93.         Class<?> demo=null;  
  94.         try {  
  95.             Document doc=builder.build(this.recoverObjextXmlFile);  
  96.             Element object=doc.getRootElement();  
  97.             this.clazzName = object.getAttributeValue("class");  
  98.             demo=Class.forName(this.clazzName);  
  99.             O o = (O) demo.newInstance();  
  100.             List propertiesList = object.getChildren("property");  
  101.             for(Iterator iter = propertiesList.iterator(); iter.hasNext();){  
  102.                 Element attr = (Element) iter.next();  
  103.                 String attrName = attr.getAttributeValue("name");  
  104.                 String attrValue = attr.getChildText("value");  
  105.                 Field f= demo.getDeclaredField(attrName);  
  106.                 f.setAccessible(true);  
  107.                 Class<?> type = f.getType();  
  108.                 if(type.equals(String.class)){  
  109.                     f.set(o, attrValue);  
  110.                 }else if(type.equals(int.class)){  
  111.                     f.set(o, Integer.parseInt(attrValue));  
  112.                 }else if(type.equals(java.util.Date.class)){  
  113.                     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
  114.                     f.set(o, format.parse(attrValue));  
  115.                 }  
  116.                   
  117.             }  
  118.             return o;  
  119.         } catch (JDOMException e) {  
  120.               
  121.             e.printStackTrace();  
  122.         } catch (IOException e) {  
  123.               
  124.             e.printStackTrace();  
  125.         } catch (ClassNotFoundException e) {  
  126.             // TODO Auto-generated catch block  
  127.             e.printStackTrace();  
  128.         } catch (InstantiationException e) {  
  129.             // TODO Auto-generated catch block  
  130.             e.printStackTrace();  
  131.         } catch (IllegalAccessException e) {  
  132.             // TODO Auto-generated catch block  
  133.             e.printStackTrace();  
  134.         } catch (NoSuchFieldException e) {  
  135.             // TODO Auto-generated catch block  
  136.             e.printStackTrace();  
  137.         } catch (SecurityException e) {  
  138.             // TODO Auto-generated catch block  
  139.             e.printStackTrace();  
  140.         } catch (IllegalArgumentException e) {  
  141.             // TODO Auto-generated catch block  
  142.             e.printStackTrace();  
  143.         } catch (ParseException e) {  
  144.             // TODO Auto-generated catch block  
  145.             e.printStackTrace();  
  146.         }  
  147.           
  148.         return null;  
  149.     }  
  150.     public static void main(String [] args){  
  151.         RecoverObject<Student> object = new RecoverObject<Student>("./source/object.properties2""./source/object.xml");  
  152.         Student s = object.get();  
  153.         System.out.println(s);  
  154.     }  
  155. }  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值