Out of curiosity I was looking at the HttpServlet class's code and found that its parent class "GenericServlet" defines the method "getServletName()" declared in the interface "ServletConfig". However the GenericServlet's getServletName() method makes a call to "sc.getServletName()" if the ServletConfig's object "sc" is not null. I could not understand how this thing works since it seems to be calling itself when I do a ctrl+click in eclipse to see the implementation of the method! There is no overridden implementation in the HttpServlet class too!
Here is a snapshot of the GenericServlet's implementation :
public String getServletName() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletName();
}
Can anybody enlighten me on this..
javax.servlet.GenericServlet
implements the ServletConfig
interface but it does not contain the actual implementation for ServletConfig
.It uses delegation by using config
object, which is provided by the container
while invoking the init
method.
GenericServlet
takes ServletConfig
object (which is a StandardWrapperFacade
obj for tomcat ) as a parameter for init(ServletConfig config)
method and store its reference to the instance variable config
when invoked by container
.
Init method
public void init(ServletConfig config) throws ServletException {
this.config = config;//assign config to the instance variable
this.init();
}
getServletName method
public String getServletName() {
ServletConfig sc = getServletConfig();//returns the ref of instance variable i.e. config
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletName();//call method on config object
}
}
Therefor it's not calling the getServletName()
on current instance( this
) instead it's calling it on config
object which is passed by the servlet container
while initialing the servlet.
You should also look at the servlet Life-Cycle.
For tomcat org.apache.catalina.core.StandardWrapper
provides the actual implementation of ServletConfig
interface.
UPDATE:-
If you want to get the name of underlying class then you could use object.getClass().getName();
method.