类名:
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("http://className").getText(); String methodName = document.selectSingleNode("http://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("http://className").getText(); String methodName = document.selectSingleNode("http://methodName").getText(); //System.out.println(className + ":" + methodName); //参数 String argType = document.selectSingleNode("http://argType").getText(); String argValue = document.selectSingleNode("http://argValue").getText(); //反射创建对象并执行方法 Class clazz = Class.forName(className); Method method = clazz.getMethod(methodName,Class.forName(argType)); method.invoke(clazz.newInstance(),argValue); }}
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶(hù)
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)