Reflection through the JAVA and JAVA DOM4J to achieve object persistence

2010-11-08  来源:本站原创  分类:Java  人气:98 

An interface ReadWriteInt, an implementation class ReadWriteIntImp, the code is as follows:

package com.netunit.workbench.util;   

import java.io.IOException;
import java.util.List;   

/**
 *  Read and write XML interface
 * @author Ming.He
 *
 * @Data 2009-12-21
 */
public interface ReadWriteInt {   

    /**
     *  Writes data to the xml file
     * @param list
     * @param cls
     * @throws IOException
     */
    public void writeXML(List list, Class cls) throws IOException;   

    /**
     *  To read out the data to 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;   

/**
 *  Read and write XML implementation
 * @author Ming.He
 *
 * @Data 2009-12-21
 */
public class ReadWriteIntImp implements ReadWriteInt {   

    /**
     *  File name
     */
    private File file ;
    /**
     *  Set the encoding
     */
    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();   // The name of the class that contains package name
        String classes = className.substring(className.lastIndexOf(".")+1,className.length());// Class name
        XMLWriter writer = null;        //  Statement writing XML object
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);   //  Set the encoding of the XML file format
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(roots);// The root node
        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();    // All field
        for (int i=0;i<field.length;i++){
            name = field[i].getName();
            tem = three.addElement(name);
            try {
                Method methodTitle = cls.getMethod(getOnetoUpperCase(name));// Locate the field get method
                tem.setText(methodTitle.invoke(object)+"");     // Perform a get method
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *  Generated get method
     * @param str
     * @return
     */
    private String getOnetoUpperCase(String str){
        return "get"+ firsttoUpperCase(str);
    }   

    /**
     *  Generate set method
     * @param str
     * @return
     */
    private String setOnetoUpperCase(String str){
        return "set"+ firsttoUpperCase(str);
    }
    /**
     *  First letter uppercase
     * @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();// The name of the class that contains package name
        String classes = className.substring(className.lastIndexOf(".")+1,className.length());// Class name
        //  Remove file
        SAXReader sr = new SAXReader();
        Document doc = sr.read(file);
        //  From the root node
        Element root = doc.getRootElement();
        //  Drop zone with node  .
        Iterator it = root.elementIterator();
        while (it.hasNext()) {
            Element two = (Element) it.next();
            //  When root nodes are equal to datas
            if (two.getName().equalsIgnoreCase(classes+"s")) {
                for (Iterator i = two.elementIterator(); i.hasNext();) {
                    Element three = (Element) i.next();
                    Object object = cls.newInstance(); // Create object
                    Element element  = null ;
                    Field[] field ;
                    for (Iterator y = three.elementIterator(); y.hasNext();){
                        element = (Element) y.next();
                        field = cls.getDeclaredFields();    // All field
                        for (int tem=0;tem<field.length;tem++){
                            if (field[tem].getName().equals(element.getName())){
                                field[tem].setAccessible(true);   // Set the properties you can modify the
                                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();
        }
    }
}

Efficiency: 1W seconds, 10W overflow

相关文章
  • Reflection through the JAVA and JAVA DOM4J to achieve object persistence 2010-11-08

    An interface ReadWriteInt, an implementation class ReadWriteIntImp, the code is as follows: package com.netunit.workbench.util; import java.io.IOException; import java.util.List; /** * Read and write XML interface * @author Ming.He * * @Data 2009-12-

  • Influence far beyond imagination Java - Why Java platform to be adopted 2009-09-17

    Types of development projects from the perspective of the java platform is based on B / S structure of the system, in the direction of the competition is fierce, there is this focus on the LAMP (Linux + Apache + Mysql + Php); also just the rise of Ra

  • java call java web service 2009-11-23

    written in java called java basic web service, including two big: The first step is to create a web service The second is to create a client to call the above to create a good web service Concrete steps are as follows: How to create a Web Services 1,

  • JAVA Skills: JAVA common abnormalities 2010-03-29

    1. Java.lang.nullpointerexception The exception I am sure you are frequently encountered, unusual explanation is that "program has encountered a null pointer," is simply called without initializing the object or the object does not exist, this e

  • java multi-threading - java. util.concurrent.locks.AbstractQueuedSynchronizer resolution (only with multi-thread synchronization example) 2009-10-05

    jdk1.5 and jdk1.6 multi-threading api is somewhat different, this is mainly for the jdk1.5 multi-threaded api's AbstractQueuedSynchronizer explanation. jdk api Many locks are achieved and used within AbstractQueuedSynchronizer achieved. AbstractQueue

  • Learning Java for Java development environment installed and properly configured 2010-07-18

    Recently in the "know" to resolve the problem, encountered many and the Java environment configuration-related issues. Feel the need to write something, because tapping the answer the same question, the hand is not tired, tired brain. Write the

  • java API provides methods to achieve order, such as file size and sort by date 2010-08-02

    java API provides methods to achieve order, such as file size and sort by date 2008-10-06 23:25 Abstract: The often see people still take the trouble of using bubble (the most common!) Or exchange to rank, in fact, with a few lines of code to achieve

  • java regular Java: Web Application timing tasks to achieve an easy way to (switch) 2010-10-15

    java regular Java: Web Application timing tasks to achieve an easy way to (switch) WEB application in the regular task to achieve an easy way to In web mode, if we are to achieve on a regular basis to perform certain tasks, then, in addition to quart

  • JAVA based (Java argument passed by value or reference) 2010-10-27

    Parameter by value rather than the instructions passed by reference and only Java application has a parameter passing mechanism, that is passed by value. Writing it is to expose the common myth that Java applications that pass parameters by reference

  • Free open-source Java database. Java embedded database. Java memory database 2010-11-02

    HSQLDB HSQLDB (Hypersonic SQL) is a pure Java relational database development, and provides JDBC driver to access the data. Support the ANSI-92 standard SQL syntax. And he accounts for a small space. Only about 160K, with a fast database engine. Axio

  • With edtftpj Java FTP client tool to achieve 2010-12-15

    http://lavasoft.blog.51cto.com/62575/101108 With edtftpj Java FTP client tool to achieve edtftpj is a java FTP kit, easy to use, easy to use and feel than the Apache, but Apache is more flexible. edtftpj there are several versions, namely, java,. net

  • java serialization java.io.Externalizable 2010-12-27

    This time we are talking about is the control of object serialization and deserialization of the control sequence is a sequence of objects to choose, rather than the content of the object are serialized so, the first chapter introduces the example of

  • Several Java database connection pool to achieve (a) 2011-08-31

    Several Java database connection pool to achieve (a) (A) package shop; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; / * java database connection pool implementation (reproduced) Role

  • Java Annotation(Java 注解)的实现代码 2014-02-01

    本篇文章介绍了,Java Annotation(Java 注解)的实现代码.需要的朋友参考下 如果你想知道java annotation是什么?你可以先看看:"http://www.infoq.com/articles/Annotation-Hammer" 下面是我做的一个demo: 项目结构: 运行效果: ==================================================== 代码部分: 注:很多人会考虑这个问题,"这样做的目的是什么?我们

  • 图说 Java:理解 Java 机制最受欢迎的 8 幅图 2013-10-30

    世间总是一图胜过千万言,下面的8幅图来自于 Program Creek 的 Java教程 ,目前这是该网站最受欢迎的文章. 希望本文能帮你回顾你已经知道的那些知识.如果图片讲解的不够清晰,你可能需要阅读详细的文章或者进行搜索. 1. 字符串的不可变性(String Immutability) String s = "abcd"; s = s.concat("ef"); 下图显示了如下代码运行的过程: 中文参考:Java String 详解 2. equals() 与

  • [Java 泥水匠] Java Components 之二:算法篇之项目实践中的位运算符(有你不懂的 2014-12-05

    作者:泥沙砖瓦浆木匠 个人签名:打算起手不凡写出鸿篇巨作的人,往往坚持不了完成第一章节. 如果我的帮到了你,是否乐意捐助一下或请一杯啤酒也好呢?有你支持,干的更好~ 点这参与众筹 我的支付宝:13958686678 2.1 前言 自从上篇[Java 泥水匠] Java Components 之一:Java String (肯定有你不懂的泥瓦匠很快又和你们聊起来了.写的还不错~ 要时刻对自己说: 得到殊荣也是昨天,看在眼里的只有今天.等待明天的只有死亡和坟墓. 回到正题,今天是讲位运算的,肯定有你

  • Little reflection on the knowledge of JAVA 2010-05-12

    Reflection Package: java.lang.reflect, provides classes and interfaces in order to obtain information about classes and objects of reflection information. The role of reflection: the security restrictions, the reflection to allow programmatic access

  • Reflection on the java code java reflection notes and destruction of object-oriented description of package 2010-08-01

    Student entity class: package com.vision.reflect; public class Student ( private String name; private int age; public Student () () public Student (String name, int age) ( this.name = name; this.age = age; ) public void setName (String name) ( this.n

  • 在java中使用dom4j解析xml(示例代码) 2015-04-15

    鉴于目前的趋势,我们这里来讲讲Dom4j的基本用法,不涉及递归等复杂操作.Dom4j的用法很多,官网上的示例有那么点儿晦涩,这里就不写了 虽然Java中已经有了Dom和Sax这两种标准解析方式 但其操作起来并不轻松,对于我这么一个初学者来说,其中部分代码是活生生的恶心 为此,伟大的第三方开发组开发出了Jdom和Dom4j等工具 鉴于目前的趋势,我们这里来讲讲Dom4j的基本用法,不涉及递归等复杂操作 Dom4j的用法很多,官网上的示例有那么点儿晦涩,这里就不写了 首先我们需要出创建一个xml文档

  • Java Session is how to achieve the 2010-03-29

    Study of these days in the next Session of the java implementations, in javaeye terms of a good post, very helpful to me, buaawhl answer is very detailed and address: http://www.javaeye.com/ topic/10452 # 57430. Later, after its own research found th