为了账号安全,请及时绑定邮箱和手机立即绑定

java反射获取xml元素

标签:
Java

类名:

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()");    }}

配置文件:

<?xml version="1.0" encoding="UTF-8"?><root>    <class>        <className>day2.mode1.Person</className>        <methodName>jump</methodName>        <argType>java.lang.String</argType>        <argValue>李玟</argValue>    </class></root>

测试类:

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);        }}

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消