Are there object creation expressions in Java similar to those in C #?

In C #, I can instantiate each custom class that I write and pass values ​​for its members, for example:

public class MyClass { public int number; public string text; } var newInstance = new MyClass { number = 1, text = "some text" }; 

This way to create objects is called object creation expressions . Is there a way that I can do the same in Java? I want to pass values ​​for arbitrary public class members.

+8
java object constructor c #
source share
2 answers

No, there is nothing like it. The closest you can come to Java (without writing a builder class, etc.) is to use an anonymous inner class and an initializer block, which is terrible, but it works:

 MyClass foo = new MyClass() {{ number = 1; text = "some text"; }}; 

Note the double braces ... one to indicate "this is the contents of an anonymous inner class" and one to indicate an initializer block. I would not recommend this style personally.

+10
source share

Not. But I do not find the following code too detailed

 MyClass obj = new MyClass(); obj.number = 1; obj.text = "some text"; 

Or the good old constructor, causing too confusing

 MyClass obj = new MyClass(1, "some text"); 

Some may suggest a chain of methods:

 MyClass obj = new MyClass().number(1).text("some text"); class MyClass int number public MyClass number(int number){ this.number=number; return this; } 

which requires an additional method for each field. This boiler plate code, IDE can help here.

Then there is a builder pattern that works even more for the author of the API.

0
source share

All Articles