How does method chaining work?

2019-01-20 20:40发布

问题:

How does getRequestDispatcher("xxx") get called from getServletContext() in the example below? How does calling procedures like this work in general? Please give me a clear picture about this context.

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.include(request, response);

回答1:

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");


回答2:

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.