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.GenericServletimplements theServletConfiginterface but it does not contain the actual implementation forServletConfig.It uses delegation by usingconfigobject, which is provided by thecontainerwhile invoking theinitmethod.GenericServlettakesServletConfigobject (which is aStandardWrapperFacadeobj for tomcat ) as a parameter forinit(ServletConfig config)method and store its reference to the instance variableconfigwhen invoked bycontainer.Init method
getServletName method
Therefor it's not calling the
getServletName()on current instance(this) instead it's calling it onconfigobject which is passed by theservlet containerwhile initialing the servlet.You should also look at the servlet Life-Cycle.
For tomcat
org.apache.catalina.core.StandardWrapperprovides the actual implementation ofServletConfiginterface.UPDATE:-
If you want to get the name of underlying class then you could use
object.getClass().getName();method.