How does method chaining work?

后端 未结 2 1012
别那么骄傲
别那么骄傲 2020-12-12 08:02

How does getRequestDispatcher(\"xxx\") get called from getServletContext() in the example below? How does calling procedures like this work in gene

相关标签:
2条回答
  • 2020-12-12 08:47

    in general, method chaining is a good practice achieving fluent and flexible interfaces. Generally... to achieve it, you just do your code and return the current object. For example, in Java:

    public Criterios<T> setOrdem(String campo, String direcao) {
        getOrdenacao().set(campo, direcao);
        return this;
    }
    
    public Criterios<T> setOrdem(String campo) {
        return setOrdem(campo, Ordenacao.Direcao.ASC);
    }
    
    public final Criterios<T> setPagina(int pagina) {
        getPaginacao().setPagina(pagina);
        return this;
    }
    
    public final Criterios<T> setQuantidade(int quantidade) {
        getPaginacao().setQuantidade(quantidade);
        return this;
    }
    

    Returning the current object provides the same API over and over... but, by each iteration the object gets changed, step by step, orderly.

    0 讨论(0)
  • 2020-12-12 08:59

    getServletContext() returns a ServletContext object, which has a method called getRequestDispatcher(). Your line of code is just shorthand for two method calls, and is equivalent to this code:

    ServletContext context = getServletContext();
    RequestDispatcher dispatcher = context.getRequestDispatcher("/index.jsp");
    
    0 讨论(0)
提交回复
热议问题