【发布时间】:2014-09-25 13:22:19
【问题描述】:
出于好奇,我查看了 HttpServlet 类的代码,发现它的父类“GenericServlet”定义了接口“ServletConfig”中声明的方法“getServletName()”。 但是,如果 ServletConfig 的对象“sc”不为空,则 GenericServlet 的 getServletName() 方法会调用“sc.getServletName()”。我无法理解这个东西是如何工作的,因为当我在 eclipse 中按 ctrl+click 来查看方法的实现时,它似乎在调用自己! HttpServlet 类中也没有重写实现!
这是 GenericServlet 实现的快照:
public String getServletName() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletName();
}
任何人都可以告诉我这个..
【问题讨论】:
-
这不是自称。 GenericServlet 调用的是 servletConfig.getServletName() 而不是 this.getServletName()。碰巧 GenericServlet 为了方便也实现了 ServletConfig 接口,但它不是 servletConfig。它通过它的 init(ServletConfig config) 方法获取 serveltConfig 对象。然后在 getServletName() 方法中,它只是充当代理将此调用传递给 config.getServletName() 方法。这里有什么不明白的地方??
-
是的,你是对的@Gas,但我没有得到的是它如何返回 servlet 的名称,因为 ServletConfig 的 getServletName() 只是一个抽象方法。此外,如果我们在 GenericServlet 类中按住 ctrl+单击“sc.getServletName()”来查看它的实现,我们会再次使用相同的方法!我想知道本质上从哪里返回字符串(Servlet的名称)..