Java method call chaining in static context

2019-06-18 15:35发布

In StringBuilder class I can do like this:

StringBuilder sb = new StringBuilder();
sb.append( "asd").append(34);

method append returns StringBuilder instance, and I can continuosly call that.

My question is it possible to do so in static method context? without class instance

5条回答
Ridiculous、
2楼-- · 2019-06-18 16:07

This is called method-chaining.

To do it, you always need an instantiated object. So, sorry, but you cannot do it in a static context as there is no object associated with that.

查看更多
Viruses.
3楼-- · 2019-06-18 16:20

You want the builder pattern on a static? No. Best to convert your statics to instances.

查看更多
Animai°情兽
4楼-- · 2019-06-18 16:25

Do you want this ?

public class AppendOperation() {
    private static StringBuilder sb =  new StringBuilder(); 

    public static StringBuilder append(String s){
        return sb.append(s);
    }

    public static void main(String... args){

         System.out.println(AppendOperation.append("ada").append("dsa").append("asd"));

    }

}

maybe I don't understand the question (static context) correctly

do you mean this?

static {

} //of course you can do this, too

if not all above, you can't do without any static method because append() is not static

查看更多
一夜七次
5楼-- · 2019-06-18 16:33

As said here You can simply return null. For example:

public class MyClass {

    public static MyClass myMethod() {
        doSomething();
        return null;
    }
}
查看更多
来,给爷笑一个
6楼-- · 2019-06-18 16:34

Yes. Like this (untested).

public class Static {

  private final static Static INSTANCE = new Static();

  public static Static doStuff(...) {
     ...;
     return INSTANCE;
  }

  public static Static doOtherStuff() {
    ....
    return INSTANCE;
  }
}

You can now have code like.

Static.doStuff(...).doOtherStuff(...).doStuff(...);

I would recommend against it though.

查看更多
登录 后发表回答