有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在一条语句中链接多个java方法调用?

我想做点什么 而不是

MyClass myclass = new MyClass();

myclass.params(url,body);
myclass.request(); 
myclass.response();

调用该类中的函数

我希望它像

MyClass myclass = new MyClass();

myclass.params(url,body).request().response();

如果可能的话


共 (1) 个答案

  1. # 1 楼答案

    这是一个完全正确的问题,是的:这是可能的

    api风格的类型称为流畅接口。从wikipedia

    A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call

    要为您的用例实现这一点,只需像下面这样声明您的方法:

    public MyClass params(String url, String body) {
        // your code here
        return this;
    }
    

    相反:

    public void params(String url, String body) {
        // your code here
    }