Class Name:
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()"); }}
Configuration file:
<?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>
Test class:
Import Java.io.file;import java.lang.reflect.method;import Org.dom4j.document;import Org.dom4j.io.SAXReader;import org.junit.test;//use DOM4J and reflection technology public class Demo1 {//parse XML file @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); Reflection creates an object and executes the method Class Clazz = Class.forName (className); method = Clazz.getmethod (Methodname,null); Method.invoke (clazz.newinstance (), NULL); }//Parse XML file parameter @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); Parameter String Argtype = Document.selectsinglenode ("//argtype"). GetText (); String Argvalue = Document.selectsinglenode ("//argvalue"). GetText (); Reflection creates an object and executes the method Class Clazz = Class.forName (className); method = Clazz.getmethod (Methodname,class.forname (Argtype)); Method.invoke (Clazz.newinstance (), argvalue); }}
Java reflection get XML element