| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 971 人关注过本帖
标题:【原创】利用Java反射来执行XML文件中定义的处理
只看楼主 加入收藏
日知己所无
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:贵宾
威 望:38
帖 子:427
专家分:2071
注 册:2014-3-22
结帖率:92.86%
收藏
 问题点数:0 回复次数:1 
【原创】利用Java反射来执行XML文件中定义的处理
C:\main.xml
程序代码:
<flow>
    <internalvariable>
        <caculateresult>0</caculateresult>
        <executeresult>OK</executeresult>
    </internalvariable>
    <class>
        <name>ClassAdd</name>
        <method>execute</method>
        <parameter>
            <leftvalue>6</leftvalue>
            <rightvalue>5</rightvalue>
        </parameter>
        <returnvalue>
            <caculateresult>caculateresult</caculateresult>
            <executeresult>executeresult</executeresult>
        </returnvalue>
    </class>
    <class>
        <name>ClassSubtract</name>
        <method>execute</method>
        <parameter>
            <leftvalue>caculateresult</leftvalue>
            <rightvalue>4</rightvalue>
        </parameter>
        <returnvalue>
            <caculateresult>caculateresult</caculateresult>
            <executeresult>executeresult</executeresult>
        </returnvalue>
    </class>
    <class>
        <name>ClassMultiply</name>
        <method>execute</method>
        <parameter>
            <leftvalue>caculateresult</leftvalue>
            <rightvalue>3</rightvalue>
        </parameter>
        <returnvalue>
            <caculateresult>caculateresult</caculateresult>
            <executeresult>executeresult</executeresult>
        </returnvalue>
    </class>
    <class>
        <name>ClassDivide</name>
        <method>execute</method>
        <parameter>
            <leftvalue>caculateresult</leftvalue>
            <rightvalue>2</rightvalue>
        </parameter>
        <returnvalue>
            <caculateresult>caculateresult</caculateresult>
            <executeresult>executeresult</executeresult>
        </returnvalue>
    </class>
</flow>

ClassAdd.java
程序代码:
import java.math.BigDecimal;
import java.util.HashMap;

public class ClassAdd {
    public static HashMap<String, String> execute(HashMap<String, String> inputMap) {
        HashMap<String, String> outputMap = new HashMap<String, String>();

        try {
            outputMap.put("executeresult", "NG");

            BigDecimal leftvalue = new BigDecimal((String)inputMap.get("leftvalue"));
            BigDecimal rightvalue = new BigDecimal((String)inputMap.get("rightvalue"));
            String caculateresult = leftvalue.add(rightvalue).toString();

            outputMap.put("caculateresult", caculateresult);

            outputMap.put("executeresult", "OK");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputMap;
    }
}

ClassSubtract.java
程序代码:
import java.math.BigDecimal;
import java.util.HashMap;

public class ClassSubtract {
    public static HashMap<String, String> execute(HashMap<String, String> inputMap) {
        HashMap<String, String> outputMap = new HashMap<String, String>();

        try {
            outputMap.put("executeresult", "NG");

            BigDecimal leftvalue = new BigDecimal((String)inputMap.get("leftvalue"));
            BigDecimal rightvalue = new BigDecimal((String)inputMap.get("rightvalue"));
            String caculateresult = leftvalue.subtract(rightvalue).toString();

            outputMap.put("caculateresult", caculateresult);

            outputMap.put("executeresult", "OK");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputMap;
    }
}

ClassMultiply.java
程序代码:
import java.math.BigDecimal;
import java.util.HashMap;

public class ClassMultiply {
    public static HashMap<String, String> execute(HashMap<String, String> inputMap) {
        HashMap<String, String> outputMap = new HashMap<String, String>();

        try {
            outputMap.put("executeresult", "NG");

            BigDecimal leftvalue = new BigDecimal((String)inputMap.get("leftvalue"));
            BigDecimal rightvalue = new BigDecimal((String)inputMap.get("rightvalue"));
            String caculateresult = leftvalue.multiply(rightvalue).toString();

            outputMap.put("caculateresult", caculateresult);

            outputMap.put("executeresult", "OK");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputMap;
    }
}

ClassDivide.java
程序代码:
import java.math.BigDecimal;
import java.util.HashMap;

public class ClassDivide {
    public static HashMap<String, String> execute(HashMap<String, String> inputMap) {
        HashMap<String, String> outputMap = new HashMap<String, String>();

        try {
            outputMap.put("executeresult", "NG");

            BigDecimal leftvalue = new BigDecimal((String)inputMap.get("leftvalue"));
            BigDecimal rightvalue = new BigDecimal((String)inputMap.get("rightvalue"));
            String caculateresult = leftvalue.divide(rightvalue).toString();

            outputMap.put("caculateresult", caculateresult);

            outputMap.put("executeresult", "OK");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputMap;
    }
}

Main.java
程序代码:
import *;
import java.util.*;
import java.util.Map.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Main {
    public static void main(String[] args) {
        try {
            excute("C:/main.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public static void excute(final String XML_FILE_PATH) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        File file = new File(XML_FILE_PATH);
        if (!(file.exists() && file.isFile())) { return; }
        Document document = documentBuilder.parse(file);
        Element element = document.getDocumentElement();

        HashMap<String, String> internalvariableMap = new HashMap<String, String>(); // 内部变量
        NodeList elementChildNodeList = element.getChildNodes();
        for (int elementChildNodeIndex = 0;
                 elementChildNodeIndex < elementChildNodeList.getLength();
                 elementChildNodeIndex++) {
            Node elementChildNode = elementChildNodeList.item(elementChildNodeIndex);
            if (elementChildNode instanceof Element) {
                if ("internalvariable".equals(elementChildNode.getNodeName())) {
                    NodeList internalvariableNodeList = elementChildNode.getChildNodes();
                    for (int internalvariableNodeIndex = 0;
                             internalvariableNodeIndex < internalvariableNodeList.getLength();
                             internalvariableNodeIndex++) {
                        Node internalvariableNode = internalvariableNodeList.item(internalvariableNodeIndex);
                        if (internalvariableNode instanceof Element) {
                            internalvariableMap.put(
                                internalvariableNode.getNodeName(),
                                internalvariableNode.getTextContent()
                            );
                        }
                    }
                } else if ("class".equals(elementChildNode.getNodeName())) {
                    String classname = ""; // 类名称
                    String methodname = ""; // 方法名称
                    HashMap<String, String> parameterMap = new HashMap<String, String>(); // 参数
                    HashMap<String, String> returnvalueMap = new HashMap<String, String>(); // 返回值
                    NodeList classNodeList = elementChildNode.getChildNodes();
                    for (int classNodeIndex = 0;
                             classNodeIndex < classNodeList.getLength();
                             classNodeIndex++) {
                        Node classNode = classNodeList.item(classNodeIndex);
                        if (classNode instanceof Element) {
                            if ("name".equals(classNode.getNodeName())) {
                                classname = classNode.getTextContent();
                            } else if ("method".equals(classNode.getNodeName())) {
                                methodname  = classNode.getTextContent();
                            } else if ("parameter".equals(classNode.getNodeName())) {
                                NodeList parameterNodeList = classNode.getChildNodes();
                                for (int parameterNodeIndex = 0;
                                         parameterNodeIndex < parameterNodeList.getLength();
                                         parameterNodeIndex++) {
                                    Node parameterNode = parameterNodeList.item(parameterNodeIndex);
                                    if (parameterNode instanceof Element) {
                                        parameterMap.put(
                                            parameterNode.getNodeName(),
                                            parameterNode.getTextContent()
                                        );
                                    }
                                }
                            } else if ("returnvalue".equals(classNode.getNodeName())) {
                                NodeList returnvalueNodeList = classNode.getChildNodes();
                                for (int returnvalueNodeIndex = 0;
                                         returnvalueNodeIndex < returnvalueNodeList.getLength();
                                         returnvalueNodeIndex++) {
                                    Node returnvalueNode = returnvalueNodeList.item(returnvalueNodeIndex);
                                    if (returnvalueNode instanceof Element) {
                                        returnvalueMap.put(
                                            returnvalueNode.getNodeName(),
                                            returnvalueNode.getTextContent()
                                        );
                                    }
                                }
                            } else { System.out.println("unexpected classNode"); }
                        }
                    } // for classNodeIndex

                    if (classname.length() > 0 && methodname.length() > 0) {
                        HashMap<String, String> inputMap = new HashMap<String, String>();
                        HashMap<String, String> outputMap = new HashMap<String, String>();

                        Iterator<?> parameterMapIterator = parameterMap.entrySet().iterator();
                        while (parameterMapIterator.hasNext()) {
                            Entry<String, String> parameterMapEntry = (Entry<String, String>) parameterMapIterator.next();
                            if (internalvariableMap.containsKey(parameterMapEntry.getValue())) {
                                // 如果参数值是内部变量的名字的话,把相应的内部变量的值作为参数传递
                                inputMap.put(
                                        parameterMapEntry.getKey(),
                                        internalvariableMap.get(parameterMapEntry.getValue()));
                            } else {
                                // 如果参数值不是内部变量的名字的话,直接作为参数传递
                                inputMap.put(
                                        parameterMapEntry.getKey(),
                                        parameterMapEntry.getValue());
                            }
                        }
                        System.out.print(classname + "." + methodname + "\t" + inputMap);

                        outputMap = (HashMap<String, String>) Class.forName(classname).getDeclaredMethod(methodname, HashMap.class).invoke(null, inputMap);

                        Iterator<?> returnvalueMapIterator = returnvalueMap.entrySet().iterator();
                        while (returnvalueMapIterator.hasNext()) {
                            Entry<String, String> returnvalueMapEntry = (Entry<String, String>) returnvalueMapIterator.next();
                            if (internalvariableMap.containsKey(returnvalueMapEntry.getValue())) {
                                // 如果返回值是内部变量的名字的话,把相应的返回值保存到内部变量中
                                internalvariableMap.put(returnvalueMapEntry.getKey(), outputMap.get(returnvalueMapEntry.getKey()));
                            }
                        }
                        System.out.println("\treturn" + outputMap);
                    } else { System.out.println("classname or methodname is undefined"); }
                } else { System.out.println("unexpected elementChildNode"); }
            }
        }
    }
}
搜索更多相关主题的帖子: method Java 
2014-12-14 15:38
日知己所无
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:贵宾
威 望:38
帖 子:427
专家分:2071
注 册:2014-3-22
收藏
得分:0 
ClassAdd / ClassSubtract / ClassMultiply / ClassDivide.java分别为负责执行加减乘除四则运算的类。

main.xml里面定义了具体的执行顺序。【示例为:((6+5)-4)*3/2,结果为:10.5】

Main.java负责解析main.xml文件,通过反射来执行四则运算,并传递参数、处理返回值。
下面是运行结果:
ClassAdd.execute    {leftvalue=6, rightvalue=5}    return{caculateresult=11, executeresult=OK}
ClassSubtract.execute    {leftvalue=11, rightvalue=4}    return{caculateresult=7, executeresult=OK}
ClassMultiply.execute    {leftvalue=7, rightvalue=3}    return{caculateresult=21, executeresult=OK}
ClassDivide.execute    {leftvalue=21, rightvalue=2}    return{caculateresult=10.5, executeresult=OK}
2014-12-14 15:45
快速回复:【原创】利用Java反射来执行XML文件中定义的处理
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.033801 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved