反射机制
reflect.java
<code>
http://blog.csdn.net/redarmy_chen/article/details/12969219
package dom4jreflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import dom4j.dom4jtest;
public class refelct {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void jiexi() throws NoSuchMethodException, SecurityException
{
{
Document document = null;
try {
document = new SAXReader().read(dom4jtest.class.getClassLoader().getResourceAsStream("reflect.xml"));
Element root =document.getRootElement();
Element servlet = root.element("servlet");
String personclasss=servlet.elementText("servlet-class");
Class test=Class.forName(personclasss);
Object object=test.newInstance();
Method method=test.getMethod("eat", null);
method.invoke(object, null);
//反射执行方法
} catch (DocumentException | ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
</code>
测试类
<code>
package dom4jreflect;
public class person {
public void eat()
{
System.out.println("eating!!!!!!!!");
}
}
</code>
测试xml
<code>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://www.example.org/web-app_2_5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name >person</servlet-name>
<servlet-class>dom4jreflect.person</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>person</servlet-name>
<url-pattern>/person</url-pattern>
</servlet-mapping>
</web-app>
</code>