ITPub博客

首页 > IT职业 > IT图书 > java反射获取xml元素

java反射获取xml元素

IT图书 作者:cbjly 时间:2021-09-09 09:55:00 0 删除 编辑

类名:

class Person {    public void run(String who){        System.out.println("Person::run()" + who);    }    public void jump(String who){        System.out.println("Person::jump()" + who);    }    public void run(){        System.out.println("Person::run()");    }    public void jump(){        System.out.println("Person::jump()");    }}

配置文件:

            day2.mode1.Person        jump        java.lang.String        李玟    

测试类:

import java.io.File;import java.lang.reflect.Method;import org.dom4j.Document;import org.dom4j.io.SAXReader;import org.junit.Test;//使用dom4j和反射技术public class Demo1 {    //解析xml文件    @Test    public void fanse() throws Exception    {        SAXReader saxReader = new SAXReader();        Document document = saxReader.read(new File("src/day2/mode1/config.xml"));        String className = document.selectSingleNode("//className").getText();        String methodName = document.selectSingleNode("//methodName").getText();        //System.out.println(className + ":" + methodName);        //反射创建对象并执行方法        Class clazz = Class.forName(className);        Method method = clazz.getMethod(methodName,null);        method.invoke(clazz.newInstance(),null);    }       //解析xml文件  参数        @Test        public void fanse2() throws Exception        {            SAXReader saxReader = new SAXReader();            Document document = saxReader.read(new File("src/day2/mode1/config.xml"));            String className = document.selectSingleNode("//className").getText();            String methodName = document.selectSingleNode("//methodName").getText();            //System.out.println(className + ":" + methodName);            //参数            String argType = document.selectSingleNode("//argType").getText();            String argValue = document.selectSingleNode("//argValue").getText();            //反射创建对象并执行方法            Class clazz = Class.forName(className);            Method method = clazz.getMethod(methodName,Class.forName(argType));            method.invoke(clazz.newInstance(),argValue);        }}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2831/viewspace-2814347/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: github 常见异常
请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    85
  • 访问量
    715