使用反射机制恢复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文件

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);
	}
}

猜你在找的XML相关文章