Java method call chain in a static context

In the StringBuilder class, I can do like this:

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

The append method returns an instance of StringBuilder, and I can call it constantly.

My question is: is it possible to do this in the context of a static method? without class instance

+6
source share
5 answers

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 may now have a code.

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

I would recommend against this.

+11
source

This is called a chain of methods.

To do this, you always need an instance of the object. So, sorry, but you cannot do this in a static context, because you are not associated with this object.

+7
source

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

Perhaps I do not understand the question (static context) correctly

Do you mean this?

static {

} // Of course you can do it too

If not all of the above, you cannot do without any static method, because append () is not static

+2
source

Do you need a static builder pattern? No. It is best to convert your statics to instances.

+2
source

As said here, you can just return null . For instance:

 public class MyClass { public static MyClass myMethod() { doSomething(); return null; } } 
0
source

Source: https://habr.com/ru/post/1332596/


All Articles