官术网_书友最值得收藏!

Spring框架內(nèi)部大量使用反射與操作XML技術(shù),以至于MyBatis也高度依賴這兩種技術(shù)。掌握這兩種技術(shù)有助于高效理解與學(xué)習(xí)Java EE框架。

本書的全部案例均在IntelliJ IDEA開發(fā)工具中進行測試,項目類型為Maven。

本節(jié)介紹反射技術(shù)的基本使用,創(chuàng)建maven-archetype-quickstart類型的Maven項目reflectTest。

創(chuàng)建實體類Userinfo,代碼如下:

package com.ghy.www.entity;

public class Userinfo {

    private long id;
    private String username;
    private String password;

    public Userinfo() {
        System.out.println("public Userinfo()");
    }

    public Userinfo(long id) {
        super();
        this.id = id;
    }

    public Userinfo(long id, String username) {
        super();
        this.id = id;
        this.username = username;
    }

    public Userinfo(long id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        System.out.println("public Userinfo(long id, String username, String password)");
        System.out.println(id + " " + username + " " + password);

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void test() {
        System.out.println("public void test1()");
    }

    public void test(String address) {
        System.out.println("public void test2(String address) address=" + address);
    }

    public String test(int age) {
        System.out.println("public String test3(int age) age=" + age);
        return "我是返回值";
    }
}

創(chuàng)建實體類Userinfo2,代碼如下:

package com.ghy.www.entity;

public class Userinfo2 {

    private long id;
    private String username;
    private String password;

    private Userinfo2() {
        System.out.println("public Userinfo()");
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

1.正常創(chuàng)建對象并調(diào)用方法

正常創(chuàng)建對象并調(diào)用方法的寫法如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

public class Test1 {
    public static void main(String[] args) {
        Userinfo userinfo = new Userinfo();
        userinfo.setId(100);
        userinfo.setUsername("中國");
        userinfo.setPassword("中國人");

        System.out.println(userinfo.getId());
        System.out.println(userinfo.getUsername());
        System.out.println(userinfo.getPassword());
    }
}

但在某些情況下,預(yù)創(chuàng)建對象的類名以字符串的形式存儲在XML文件中,比如Servlet技術(shù)中的web.xml文件部分的示例代碼如下:

<servlet>
    <servlet-name>InsertUserinfo</servlet-name>
    <servlet-class>controller.InsertUserinfo</servlet-class>
</servlet>

Servlet對象就是由Tomcat讀取這段XML配置代碼并解析出“controller.InsertUserinfo”字符串,然后使用反射技術(shù)動態(tài)創(chuàng)建出InsertUserinfo 類的對象。可見反射技術(shù)無處不在,是學(xué)習(xí)框架技術(shù)非常重要的知識點。

下面我們來模擬一下Tomcat處理的過程。

在resources文件夾中創(chuàng)建文件createClassName.txt,內(nèi)容如下:

com.ghy.www.entity.Userinfo

創(chuàng)建運行類Test2,代碼如下:

package com.ghy.www.test1;

import java.io.IOException;
import java.io.InputStream;

public class Test2 {
    public static void main(String[] args) throws IOException {
        byte[] byteArray = new byte[1000];
        InputStream inputStream = Test2.class.getResourceAsStream("/createClassName.txt");
        int readLength = inputStream.read(byteArray);
        String createClassName = new String(byteArray, 0, readLength);
        System.out.println(createClassName);
        inputStream.close();
    }
}

程序運行結(jié)果如下:

com.ghy.www.entity.Userinfo

變量createClassName存儲的就是類名“com.ghy.www.entity.Userinfo”字符串,這時如果使用圖1-1所示的代碼就是錯誤的,會出現(xiàn)編譯錯誤,Java編譯器根本不允許使用這種寫法創(chuàng)建com.ghy.www.entity.Userinfo類的對象,但需求是必須把類名“com.ghy.www.entity.Userinfo”對應(yīng)的對象創(chuàng)建出來,對于這種情況可以使用反射技術(shù)來解決。反射是在運行時獲得對象信息的一種技術(shù)。

圖片 1

圖1-1 錯誤的代碼

2.獲得Class類的對象的方式

在使用反射技術(shù)之前,必須要獲得某一個*.class類對應(yīng)Class類的對象。

Class類封裝了類的信息(屬性、構(gòu)造方法和方法等),而Class類的對象封裝了具體的*.class類中的信息(屬性、構(gòu)造方法和方法等),有了這些信息,就相當(dāng)于烹飪加工時有了制造食品的原料,就可以創(chuàng)建出類的對象。

有4種方式可以獲得Class類的對象,代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

public class Test4 {
    public static void main(String[] args) throws ClassNotFoundException {
        Class class1 = Userinfo.class;
        Class class2 = new Userinfo().getClass();
        Class class3 = Userinfo.class.getClassLoader().loadClass("com.ghy.www.entity.Userinfo");
        Class class4 = Class.forName("com.ghy.www.entity.Userinfo");
        System.out.println(class1.hashCode());
        System.out.println(class2.hashCode());
        System.out.println(class3.hashCode());
        System.out.println(class4.hashCode());
    }
}

程序運行結(jié)果如下:

public Userinfo()
460141958
460141958
460141958
460141958

從打印結(jié)果可以分析出,同一個*.class類對應(yīng)的Class類的對象是同一個,單例的。

3.通過Class對象獲得Field、Constructor和Method對象

一個*.class類包含F(xiàn)ield、Constructor和Method信息,可以通過Class對象來獲取這些信息。

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test5 {
    public static void main(String[] args) {
        Class userinfoClass = Userinfo.class;
        // 屬性列表
 Field[] a = userinfoClass.getDeclaredFields();
        System.out.println(a.length);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i].getName());
        }
        System.out.println();
        // 構(gòu)造方法列表
 Constructor[] b = userinfoClass.getConstructors();
        System.out.println(b.length);
        System.out.println();
        // 方法列表
 Method[] c = userinfoClass.getDeclaredMethods();
        System.out.println(c.length);
        for (int i = 0; i < c.length; i++) {
            System.out.println(c[i].getName());
        }
    }
}

程序運行結(jié)果如下:

3
id
username
password

4

9
getId
test
test
test
getPassword
getUsername
setPassword
setId
setUsername

4.使用Class.newInstance()方法創(chuàng)建對象

方法Class.newInstance()調(diào)用的是無參構(gòu)造方法。

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

public class Test6 {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 本實驗不用new來創(chuàng)建對象,原理就是使用反射技術(shù)
 String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        // newInstance()開始創(chuàng)建對象
 Userinfo userinfo = (Userinfo) class4.newInstance();
        userinfo.setUsername("美國");
        System.out.println(userinfo.getUsername());
    }
}

程序運行結(jié)果如下:

public Userinfo()
美國

5.對Field進行賦值和取值

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

import java.lang.reflect.Field;

public class Test7 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
        String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        Userinfo userinfo = (Userinfo) class4.newInstance();

        String fieldName = "username";
        String fieldValue = "法國";
        Field fieldObject = userinfo.getClass().getDeclaredField(fieldName);
        System.out.println(fieldObject.getName());
        fieldObject.setAccessible(true);
        fieldObject.set(userinfo, fieldValue);
        System.out.println(userinfo.getUsername());
        System.out.println(fieldObject.get(userinfo));
    }
}

程序運行結(jié)果如下:

public Userinfo()
username
法國
法國

6.獲得構(gòu)造方法對應(yīng)的Constructor對象及調(diào)用無參構(gòu)造方法

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test8 {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        Constructor constructor1 = class4.getDeclaredConstructor();
        Userinfo userinfo1 = (Userinfo) constructor1.newInstance();
        Userinfo userinfo2 = (Userinfo) constructor1.newInstance();
        Userinfo userinfo3 = (Userinfo) constructor1.newInstance();
        System.out.println(userinfo1.hashCode());
        System.out.println(userinfo2.hashCode());
        System.out.println(userinfo3.hashCode());
    }
}

程序運行結(jié)果如下:

public Userinfo()
public Userinfo()
public Userinfo()
460141958
1163157884
1956725890

7.通過Constructor對象調(diào)用有參構(gòu)造方法

示例代碼如下:

package com.ghy.www.test1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test9 {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        Constructor constructor = class4.getDeclaredConstructor(long.class, 
String.class, String.class);
        System.out.println(constructor.newInstance(11, "a1", "aa1").hashCode());
        System.out.println(constructor.newInstance(12, "a2", "aa2").hashCode());
        System.out.println(constructor.newInstance(13, "a3", "aa3").hashCode());
        System.out.println(constructor.newInstance(14, "a4", "aa4").hashCode());
    }
}

程序運行結(jié)果如下:

public Userinfo(long id, String username, String password)
11 a1 aa1
460141958
public Userinfo(long id, String username, String password)
12 a2 aa2
1163157884
public Userinfo(long id, String username, String password)
13 a3 aa3
1956725890
public Userinfo(long id, String username, String password)
14 a4 aa4
356573597

8.使用反射動態(tài)調(diào)用無參無返回值方法

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test10 {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        Userinfo userinfo = (Userinfo) class4.newInstance();
        String methodName = "test";
        Method method = class4.getDeclaredMethod(methodName);
        System.out.println(method.getName());
        method.invoke(userinfo);
    }
}

程序運行結(jié)果如下:

public Userinfo()
test
public void test1()

9.使用反射動態(tài)調(diào)用有參無返回值方法

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test11 {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        Userinfo userinfo = (Userinfo) class4.newInstance();
        String methodName = "test";
        Method method = class4.getDeclaredMethod(methodName, String.class);
        System.out.println(method.getName());
        method.invoke(userinfo, "我的地址在北京!");
    }
}

程序運行結(jié)果如下:

public Userinfo()
test
public void test2(String address) address=我的地址在北京!

10.使用反射動態(tài)調(diào)用有參有返回值方法

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.entity.Userinfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test12 {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        String newObjectName = "com.ghy.www.entity.Userinfo";
        Class class4 = Class.forName(newObjectName);
        Userinfo userinfo = (Userinfo) class4.newInstance();
        String methodName = "test";
        Method method = class4.getDeclaredMethod(methodName, int.class);
        System.out.println(method.getName());
        Object returnValue = method.invoke(userinfo, 999999);
        System.out.println("returnValue=" + returnValue);
    }
}

程序運行結(jié)果如下:

public Userinfo()
test
public String test3(int age) age=999999
returnValue=我是返回值

11.反射破壞了OOP

創(chuàng)建單例模式,代碼如下:

package com.ghy.www.objectfactory;

//單例模式
//保證當(dāng)前進程中只有1個OneInstance類的對象
public class OneInstance {
    private static OneInstance oneInstance;

    private OneInstance() {
    }

    public static OneInstance getOneInstance() {
        if (oneInstance == null) {
            oneInstance = new OneInstance();
        }
        return oneInstance;
    }
}

由于構(gòu)造方法是private(私有)的,因此不能new實例化對象,只能調(diào)用public static OneInstance getOneInstance()方法獲得自身的對象,而且可以保證單例,測試代碼如下:

package com.ghy.www.test1;

import com.ghy.www.objectfactory.OneInstance;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class Test13 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        OneInstance o1 = OneInstance.getOneInstance();
        OneInstance o2 = OneInstance.getOneInstance();
        OneInstance o3 = OneInstance.getOneInstance();
        System.out.println(o1);
        System.out.println(o2);
        System.out.println(o3);
    }
}

程序運行結(jié)果如下:

com.ghy.www.objectfactory.OneInstance@1b6d3586
com.ghy.www.objectfactory.OneInstance@1b6d3586
com.ghy.www.objectfactory.OneInstance@1b6d3586

但是,使用反射技術(shù)會破壞面向?qū)ο缶幊蹋∣OP),導(dǎo)致創(chuàng)建多個OneInstance類的對象。

示例代碼如下:

package com.ghy.www.test1;

import com.ghy.www.objectfactory.OneInstance;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test14 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        Class classRef = Class.forName("com.ghy.www.objectfactory.OneInstance");
        Constructor c = classRef.getDeclaredConstructor();
        c.setAccessible(true);
        OneInstance one1 = (OneInstance) c.newInstance();
        OneInstance one2 = (OneInstance) c.newInstance();
        System.out.println(one1);
        System.out.println(one2);
    }
}

程序運行結(jié)果如下:

com.ghy.www.objectfactory.OneInstance@1b6d3586
com.ghy.www.objectfactory.OneInstance@4554617c

這里創(chuàng)建了兩個OneInstance類的對象,沒有保證單例性。雖然構(gòu)造方法是private的,但依然借助反射技術(shù)創(chuàng)建了多個對象。

12.方法重載

使用反射可以調(diào)用重載方法。

示例代碼如下:

package com.ghy.www.test1;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test15 {
    public void testMethod(String username) {
        System.out.println("public String testMethod(String username)");
        System.out.println(username);
    }

    public void testMethod(String username, String password) {
        System.out.println("public String testMethod(String username, String password)");
        System.out.println(username + " " + password);
    }

    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        Class class15Class = Test15.class;
        Object object = class15Class.newInstance();
        Method method1 = class15Class.getDeclaredMethod("testMethod", String.class);
        Method method2 = class15Class.getDeclaredMethod("testMethod", String.class, String.class);
        method1.invoke(object, "法國");
        method2.invoke(object, "中國", "中國人");
    }
}

程序運行結(jié)果如下:

public String testMethod(String username)
法國
public String testMethod(String username, String password)
中國 中國人

提起標(biāo)記語言,人們首先會想起HTML,HTML提供了很多標(biāo)簽來實現(xiàn)Web前端界面的設(shè)計,但HTML中的標(biāo)簽并不允許自定義,如果想定義一些自己獨有的標(biāo)簽,HTML就不再可行了,這時可以使用XML來進行實現(xiàn)。

XML(eXtensible Markup Language,可擴展標(biāo)記語言)可以自定義標(biāo)記名稱與內(nèi)容,在靈活度上相比HTML改善很多,經(jīng)常用在配置以及數(shù)據(jù)交互領(lǐng)域。

在開發(fā)軟件項目時,經(jīng)常會接觸XML文件,比如web.xml文件中就有XML代碼,而Spring框架也使用XML文件存儲配置。XML代碼的主要作用就是配置。

創(chuàng)建maven-archetype-quickstart類型的Maven項目xmlTest,添加如下依賴:

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

在resources文件夾中創(chuàng)建struts.xml配置文件,代碼如下:

<mymvc>
    <actions>
        <action name="list" class="controller.List">
            <result name="toListJSP">
                /list.jsp
            </result>
            <result name="toShowUserinfoList" type="redirect">
                showUserinfoList.ghy
            </result>
        </action>

        <action name="showUserinfoList" class="controller.ShowUserinfoList">
            <result name="toShowUserinfoListJSP">
                /showUserinfoList.jsp
            </result>
        </action>
    </actions>
</mymvc>

1.解析XML文件

創(chuàng)建Reader類,代碼如下:

package com.ghy.www.test1;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

public class Reader {
    public static void main(String[] args) {
        try {
           SAXReader reader = new SAXReader();
           Document document = reader.read(reader.getClass()
                  .getResourceAsStream("/struts.xml"));

           Element mymvcElement = document.getRootElement();
           System.out.println(mymvcElement.getName());
           Element actionsElement = mymvcElement.element("actions");
           System.out.println(actionsElement.getName());
           System.out.println("");
           List<Element> actionList = actionsElement.elements("action");
           for (int i = 0; i < actionList.size(); i++) {
              Element actionElement = actionList.get(i);
              System.out.println(actionElement.getName());
              System.out.print("name="
                     + actionElement.attribute("name").getValue());
              System.out.println("action class="
                     + actionElement.attribute("class").getValue());

              List<Element> resultList = actionElement.elements("result");
              for (int j = 0; j < resultList.size(); j++) {
                 Element resultElement = resultList.get(j);
                 System.out.print("  result name="
                        + resultElement.attribute("name").getValue());
                 Attribute typeAttribute = resultElement.attribute("type");
                 if (typeAttribute != null) {
                    System.out.println(" type=" + typeAttribute.getValue());
                 } else {
                    System.out.println("");
                 }
                 System.out.println("   " + resultElement.getText().trim());
                 System.out.println("");
              }

              System.out.println("");
           }

        } catch (DocumentException e) {
           // 自動生成catch塊
 e.printStackTrace();
        }
    }
}

程序運行結(jié)果如下:

mymvc
actions

action
name=listaction class=controller.List
  result name=toListJSP
   /list.jsp

  result name=toShowUserinfoList type=redirect
   showUserinfoList.ghy

action
name=showUserinfoListaction class=controller.ShowUserinfoList
  result name=toShowUserinfoListJSP
   /showUserinfoList.jsp

2.創(chuàng)建XML文件

創(chuàng)建Writer類,代碼如下:

package com.ghy.www.test1;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;

public class Writer {

    public static void main(String[] args) {
        try {
           Document document = DocumentHelper.createDocument();
           Element mymvcElement = document.addElement("mymvc");
           Element actionsElement = mymvcElement.addElement("actions");
           //
 Element listActionElement = actionsElement.addElement("action");
           listActionElement.addAttribute("name", "list");
           listActionElement.addAttribute("class", "controller.List");

           Element toListJSPResultElement = listActionElement
                  .addElement("result");
           toListJSPResultElement.addAttribute("name", "toListJSP");
           toListJSPResultElement.setText("/list.jsp");

           Element toShowUserinfoListResultElement = listActionElement
                  .addElement("result");
           toShowUserinfoListResultElement.addAttribute("name",
                  "toShowUserinfoList");
           toShowUserinfoListResultElement.addAttribute("type", "redirect");
           toShowUserinfoListResultElement.setText("showUserinfoList.ghy");
           //

 Element showUserinfoListActionElement = actionsElement
                  .addElement("action");
           showUserinfoListActionElement.addAttribute("name",
                  "showUserinfoList");
           showUserinfoListActionElement.addAttribute("class",
                  "controller.ShowUserinfoList");

           Element toShowUserinfoListJSPResultElement = showUserinfoListActionElement
                  .addElement("result");
           toShowUserinfoListJSPResultElement.addAttribute("name",
                  "toShowUserinfoListJSP");
           toShowUserinfoListResultElement.setText("/showUserinfoList.jsp");
           //

 OutputFormat format = OutputFormat.createPrettyPrint();
           XMLWriter writer = new XMLWriter(new FileWriter("ghy.xml"), format);
           writer.write(document);
           writer.close();

        } catch (IOException e) {
           e.printStackTrace();
        }

    }

}

程序運行后在項目中創(chuàng)建ghy.xml文件,如圖1-2所示。

圖片 1

圖1-2 創(chuàng)建的ghy.xml文件

3.修改XML文件

創(chuàng)建Update類,代碼如下:

package com.ghy.www.test1;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

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

public class Update {

    public static void main(String[] args) throws IOException {
        try {
           SAXReader reader = new SAXReader();
           Document document = reader.read(reader.getClass().getResourceAsStream("/struts.xml"));
           Element mymvcElement = document.getRootElement();
           Element actionsElement = mymvcElement.element("actions");
           List<Element> actionList = actionsElement.elements("action");
           for (int i = 0; i < actionList.size(); i++) {
              Element actionElement = actionList.get(i);
              List<Element> resultList = actionElement.elements("result");
              for (int j = 0; j < resultList.size(); j++) {
                 Element resultElement = resultList.get(j);
                 String resultName = resultElement.attribute("name").getValue();
                 if (resultName.equals("toShowUserinfoList")) {
                    Attribute typeAttribute = resultElement.attribute("type");
                    if (typeAttribute != null) {
                       typeAttribute.setValue("zzzzzzzzzzzzzzzzzzzzzz");
                       resultElement.setText("xxxxxxxxxxxxxxxxxxx");
                    }
                 }
              }
           }
           OutputFormat format = OutputFormat.createPrettyPrint();
           XMLWriter writer = new XMLWriter(new FileWriter("src\\ghy.xml"), format);
           writer.write(document);
           writer.close();
        } catch (DocumentException e) {
           e.printStackTrace();
        }
    }
}

程序運行后產(chǎn)生的ghy.xml文件內(nèi)容如下:

<?xml version="1.0" encoding="UTF-8"?>
<mymvc>
    <actions>
        <action name="list" class="controller.List">
            <result name="toListJSP">/list.jsp</result>
            <result name="toShowUserinfoList" type="zzzzzzzzzzzzzzzzzzzzzz">xxxxxxxxxxxxxxxxxxx</result>
        </action>
        <action name="showUserinfoList" class="controller.ShowUserinfoList">
            <result name="toShowUserinfoListJSP">/showUserinfoList.jsp</result>
        </action>
    </actions>
</mymvc>

成功更改XML文件中的屬性值與文本內(nèi)容。

4.刪除節(jié)點

創(chuàng)建Delete類,代碼如下:

package com.ghy.www.test1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

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

public class Delete {

    public static void main(String[] args) throws IOException {
        try {
           SAXReader reader = new SAXReader();
           Document document = reader.read(reader.getClass().getResourceAsStream("/struts.xml"));
           Element mymvcElement = document.getRootElement();
           Element actionsElement = mymvcElement.element("actions");
           List<Element> actionList = actionsElement.elements("action");
           for (int i = 0; i < actionList.size(); i++) {
              Element actionElement = actionList.get(i);
              List<Element> resultList = actionElement.elements("result");
              Element resultElement = null;
              boolean isFindNode = false;
              for (int j = 0; j < resultList.size(); j++) {
                 resultElement = resultList.get(j);
                 String resultName = resultElement.attribute("name").getValue();
                 if (resultName.equals("toShowUserinfoList")) {
                    isFindNode = true;
                    break;
                 }
              }
              if (isFindNode == true) {
                 actionElement.remove(resultElement);
              }
           }
           OutputFormat format = OutputFormat.createPrettyPrint();
           XMLWriter writer = new XMLWriter(new FileWriter("src\\ghy.xml"), format);
           writer.write(document);
           writer.close();
        } catch (DocumentException e) {
           e.printStackTrace();
        }
    }

}

程序運行后產(chǎn)生的ghy.xml文件內(nèi)容如下:

<?xml version="1.0" encoding="UTF-8"?>

<mymvc>
    <actions>
        <action name="list" class="controller.List">
            <result name="toListJSP">/list.jsp</result>
        </action>
        <action name="showUserinfoList" class="controller.ShowUserinfoList">
            <result name="toShowUserinfoListJSP">/showUserinfoList.jsp</result>
        </action>
    </actions>
</mymvc>

節(jié)點被成功刪除。

5.刪除屬性

創(chuàng)建DeleteAttr類,代碼如下:

package com.ghy.www.test1;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

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

public class DeleteAttr {

    public static void main(String[] args) throws IOException {
        try {
           SAXReader reader = new SAXReader();
           Document document = reader.read(reader.getClass().getResourceAsStream("/struts.xml"));
           Element mymvcElement = document.getRootElement();
           Element actionsElement = mymvcElement.element("actions");
           List<Element> actionList = actionsElement.elements("action");
           for (int i = 0; i < actionList.size(); i++) {
              Element actionElement = actionList.get(i);
              List<Element> resultList = actionElement.elements("result");
              for (int j = 0; j < resultList.size(); j++) {
                 Element resultElement = resultList.get(j);
                 String resultName = resultElement.attribute("name").getValue();
                 if (resultName.equals("toShowUserinfoList")) {
                    Attribute typeAttribute = resultElement.attribute("type");
                    if (typeAttribute != null) {
                       resultElement.remove(typeAttribute);
                    }
                 }
              }
           }
           OutputFormat format = OutputFormat.createPrettyPrint();
           XMLWriter writer = new XMLWriter(new FileWriter("src\\ghy.xml"), format);
           writer.write(document);
           writer.close();
        } catch (DocumentException e) {
           e.printStackTrace();
        }
    }
}

程序運行后產(chǎn)生的ghy.xml文件內(nèi)容如下:

<?xml version="1.0" encoding="UTF-8"?>

<mymvc>
    <actions>
        <action name="list" class="controller.List">
            <result name="toListJSP">/list.jsp</result>
            <result name="toShowUserinfoList">showUserinfoList.ghy</result>
        </action>
        <action name="showUserinfoList" class="controller.ShowUserinfoList">
            <result name="toShowUserinfoListJSP">/showUserinfoList.jsp</result>
        </action>
    </actions>
</mymvc>

XML文件中的type屬性成功被刪除。

主站蜘蛛池模板: 东港市| 石狮市| 四子王旗| 台南县| 苏尼特右旗| 乌拉特后旗| 大同市| 江安县| 华坪县| 潍坊市| 台中县| 蓬安县| 永康市| 宁蒗| 历史| 营口市| 崇阳县| 二连浩特市| 汉川市| 曲松县| 阳山县| 馆陶县| 台北县| 临沂市| 肥城市| 秦皇岛市| 湖州市| 当涂县| 宁国市| 巧家县| 郁南县| 鹤岗市| 淳化县| 焦作市| 顺义区| 鄯善县| 郯城县| 肃南| 连云港市| 闸北区| 大城县|