Apache.Tomcat 调用Servlet原理之Class类的反射机制,用orc类解释
有一个兽人类
package com.swift.servlet; public class OrcDemo { private int hp; private int mp; private int atk; public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getMp() { return mp; } public void setMp(int mp) { this.mp = mp; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public OrcDemo() { } public OrcDemo(int hp, int mp, int atk) { super(); this.hp = hp; this.mp = mp; this.atk = atk; } public void orcInfo() { System.out.println("hp"+hp+"mp"+mp+"atk"+atk); } public static void main(String[] args) { OrcDemo orc=new OrcDemo(3000,2000,500); orc.orcInfo(); } }
原本的兽人对象使用方法:
public static void main(String[] args) { OrcDemo orc=new OrcDemo(3000,2000,500); orc.orcInfo(); }
使用Class类反射,得到兽人对象全部内容:
Class c=Class.forName("OrcDemo");
OrcDemo od=(OrcDemo)c.newInstance();
od.orcInfo();
apache.tomcat就是使用这种方法调用的Servlet
web.xml配置文件中
<servlet>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>com.swift.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo<servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
把上面的<servlet-class>com.swift.servlet.TestServlet</servlet-class>中的com.swift.servlet.TestServlet拿出来使用即可
应用到刚才写的反射代码
Class c=Class.forName("OrcDemo");
OrcDemo od=(OrcDemo)c.newInstance();
od.orcInfo();
变为
Class c=Class.forName("com.swift.servlet.TestServlet"); //ServletDemo sd=(ServletDemo)c.newInstance();/*tomcat就是因为不知道有 ServletDemo这个类,才使用反射方法,这里我们可以用他的父类,多态就可以了*/ HttpServlet hs=c.newInstance(); hs.doGet();
Never waste time any more, Never old man be a yong man