通过JAVA反射机制与DOM4J来实现持久化JAVA对象

一个接口ReadWriteInt ,一个实现类ReadWriteIntImp ,代码如下:

package com.netunit.workbench.util;   
  
import java.io.IOException;   
import java.util.List;   
  
/**  
 * 读写XML接口  
 * @author Ming.He  
 *  
 * @Data 2009-12-21  
 */  
public interface ReadWriteInt {   
  
    /**  
     * 把数据写入xml文件  
     * @param list  
     * @param cls  
     * @throws IOException  
     */  
    public void writeXML(List list, Class cls) throws IOException;   
       
    /**  
     * 把数据重xml读出来  
     * @param cls  
     * @return  
     * @throws Exception  
     */  
    public List readXML(Class cls) throws Exception;   
} 




package com.netunit.workbench.util;   
  
import java.io.File;   
import java.io.FileWriter;   
import java.io.IOException;   
import java.lang.reflect.Field;   
import java.lang.reflect.Method;   
import java.util.ArrayList;   
import java.util.Iterator;   
import java.util.List;   
  
import org.dom4j.Document;   
import org.dom4j.DocumentHelper;   
import org.dom4j.Element;   
import org.dom4j.io.OutputFormat;   
import org.dom4j.io.SAXReader;   
import org.dom4j.io.XMLWriter;   
  
/**  
 * 读写XML的实现  
 * @author Ming.He  
 *  
 * @Data 2009-12-21  
 */  
public class ReadWriteIntImp implements ReadWriteInt {   
  
    /**  
     * 文件名  
     */  
    private File file ;   
    /**  
     * 设置编码  
     */  
    private String encoding = "GBK";   
       
    private String roots = "root";   
       
    public ReadWriteIntImp(File file) {   
        this.file = file;   
    }   
       
    public void writeXML(List list, Class cls) throws IOException{   
        String className = cls.getName();   //类名包含包名   
        String classes = className.substring(className.lastIndexOf(".")+1,className.length());//类名   
        XMLWriter writer = null;        // 声明写XML的对象   
        OutputFormat format = OutputFormat.createPrettyPrint();   
        format.setEncoding(encoding);   // 设置XML文件的编码格式   
        Document document = DocumentHelper.createDocument();   
        Element root = document.addElement(roots);//根节点   
        Element two = root.addElement(classes+"s");   
        two.addAttribute("class", className);   
        Element three = null;   
        for (int i=0;i<list.size();i++){   
            three = two.addElement(classes);   
            insert(three,list.get(i),cls);   
        }   
        writer = new XMLWriter(new FileWriter(file), format);   
        writer.write(document);   
        writer.close();   
    }   
       
    private void insert(Element three,Object object,Class cls){   
        Element tem  = null;   
        String name = null;   
        Field[] field = cls.getDeclaredFields();    //所有字段   
        for (int i=0;i<field.length;i++){   
            name = field[i].getName();   
            tem = three.addElement(name);   
            try {   
                Method methodTitle = cls.getMethod(getOnetoUpperCase(name));//查找这个字段的get方法   
                tem.setText(methodTitle.invoke(object)+"");     //执行get方法   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
    }   
    /**  
     * 生成get方法  
     * @param str  
     * @return  
     */  
    private String getOnetoUpperCase(String str){   
        return "get"+ firsttoUpperCase(str);   
    }   
       
    /**  
     * 生成set方法  
     * @param str  
     * @return  
     */  
    private String setOnetoUpperCase(String str){   
        return "set"+ firsttoUpperCase(str);   
    }   
    /**  
     * 第一个字母大写  
     * @param str  
     * @return  
     */  
    private String firsttoUpperCase(String str){   
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);   
    }   
  
    public List readXML(Class cls) throws Exception{   
        List list = new ArrayList();   
        String className = cls.getName();//类名包含包名   
        String classes = className.substring(className.lastIndexOf(".")+1,className.length());//类名   
        // 取文件   
        SAXReader sr = new SAXReader();   
        Document doc = sr.read(file);   
        // 取根节点   
        Element root = doc.getRootElement();   
        // 跌带跟节点.   
        Iterator it = root.elementIterator();   
        while (it.hasNext()) {   
            Element two = (Element) it.next();   
            // 当根节点等于datas时   
            if (two.getName().equalsIgnoreCase(classes+"s")) {   
                for (Iterator i = two.elementIterator(); i.hasNext();) {   
                    Element three = (Element) i.next();   
                    Object object = cls.newInstance(); //创建对象   
                    Element element  = null ;    
                    Field[] field ;   
                    for (Iterator y = three.elementIterator(); y.hasNext();){      
                        element = (Element) y.next();                  
                        field = cls.getDeclaredFields();    //所有字段   
                        for (int tem=0;tem<field.length;tem++){   
                            if (field[tem].getName().equals(element.getName())){   
                                field[tem].setAccessible(true);   //设置属性可以修改   
                                setObject(field[tem],object,element);   
                            }   
                        }   
                    }   
                    list.add(object);   
                }   
            }   
        }   
        return list;   
    }   
       
    private void setObject(Field field,Object object,Element element){   
        try {   
            if (field.getType().toString().equals("int"))   
                field.set(object, new Integer(element.getTextTrim()));   
            else if (field.getType().toString().equals("double"))   
                field.set(object, new Double(element.getTextTrim()));   
            else if (field.getType().toString().equals("long"))   
                field.set(object, new Long(element.getTextTrim()));   
            else  
                field.set(object, element.getTextTrim());   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
}  


效率:1W两秒,10W溢出

你可能感兴趣的:(java,xml)