通熟易懂的反射机制

学习目的:
有时候,可能JDK中的方法没有在帮助文档中提供,但是通过查看源代码,却发现有这个办法,如果该方法是private私有的,所以JDK的帮助文档没有提供该方法,如果必须使用这个方法,我们可以通过反射的方式获取。
使用方式
1.this.getClass() 返回该Class对象
//第一种方式:使用对象的getClass()方法;
2.Class.forName(“类的完整名字”);
//根据类的全路径进行加载,返回该类的Class对象;
3.类.class();
//第三种方式:通过类的属性获得;
class方法**
Class c=类.getClass();
Method m=c.getMethod(“字符串”,参数.class);
method的方法
String str=(String)m.invoke(Object o,参数名);—返回该方法的返回值;
下面有一个万能的servlet例子可以做参考

public class BaseServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
//1.获取处理请求的方法名
String method = request.getParameter("method");
//2.对请求方法做非空判断(说明没传递参数method或method值为"    ")
if(method == null || method.trim().isEmpty()){
    throw new RuntimeException("请您传递参数method的值");
}

//3.获取当前Servlet对象的字节码文件对象
Class c = this.getClass();
Method m = null;
try {
    //4.再从当前Servlet的字节码文件对象中获取封装了对应请求方法的Method对象
    m = c.getMethod(method, HttpServletRequest.class,HttpServletResponse.class);

} catch (Exception e) {//说明传递的请求方法在当前Servlet中不存在
    throw new RuntimeException("请求方法:"+method+"不存在");
} 

//5.执行Method所表示的对应的请求处理方法
try {
    String result = (String) m.invoke(this, request,response);

    if(!result.contains(":")){//请求方法返回的结果字符串没有前缀,就只有路径,默认是转发
        request.getRequestDispatcher("/"+result).forward(request, response);
    }else{
        int index = result.indexOf(":");
        String fs = result.substring(0, index);
        String path = result.substring(index+1);

        if(fs.equals("f")){//转发
            request.getRequestDispatcher("/"+path).forward(request, response);
        }else if(fs.equals("s")){//重定向
            response.sendRedirect(request.getContextPath()+"/"+path);
        }else{
            response.getWriter().write("what you want to do");
        }
    }

} catch (Exception e) {//方法内部有异常
    throw new RuntimeException("请求方法:"+method+"内部异常");
}

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值