servletsservletconfig

How getServletName() works in Java?


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..


Solution

  • 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.


    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.