博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Apache.Tomcat 调用Servlet原理之Class类的反射机制,用orc类解释
阅读量:7141 次
发布时间:2019-06-28

本文共 1519 字,大约阅读时间需要 5 分钟。

有一个兽人类

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配置文件中 
    
ServletDemo
    
com.swift.servlet.TestServlet
    
ServletDemo
    
/test

把上面的
com.swift.servlet.TestServlet
中的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();

  

 
 

转载于:https://www.cnblogs.com/qingyundian/p/7466943.html

你可能感兴趣的文章
在JDBC中使用Java8的日期LocalDate、LocalDateTime
查看>>
log4j MDC用户操作日志追踪配置
查看>>
react-native 项目更名步骤
查看>>
Java多线程——<五>后台线程(daemon)
查看>>
Linux 下安装PHPunit
查看>>
delphi中接口的委托和聚合
查看>>
优化反射性能的总结(上)
查看>>
HDU 2845 Beans
查看>>
ncl 实例参考
查看>>
SqlMetal Builder V2版本
查看>>
C#中数组与ArrayList的简单使用
查看>>
Activitys, Threads, & Memory Leaks
查看>>
poj3308Paratroopers(最小割)
查看>>
关于java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream解决办法
查看>>
携程面试之后的一些感想
查看>>
[收藏] 如何阅读别人的代码
查看>>
09年全年总结
查看>>
如何实现两个人脸照片的变换
查看>>
Bigtable:一个分布式的结构化数据存储系统
查看>>
Visual Studio OpenGL 配置方法
查看>>