有一個獸人類 Class c=Class.forName("OrcDemo"); OrcDemo od=(OrcDemo)c.newInstance(); od.orcInfo(); apache.tomcat就是使用這種方法調用的Servlet ...
有一個獸人類
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();