开发者

Are there object creation expressions in Java, similar to the ones in C#?

开发者 https://www.devze.com 2023-03-16 16:08 出处:网络
In C#, I can create an instance of 开发者_开发问答every custom class that I write, and pass values for its members, like this:

In C#, I can create an instance of 开发者_开发问答every custom class that I write, and pass values for its members, like this:

public class MyClass
{
    public int number;
    public string text;
}

var newInstance = new MyClass { number = 1, text = "some text" };

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


No, there's nothing directly similar. The closest you can come in Java (without writing a builder class etc) is to use an anonymous inner class and initializer block, which is horrible but works:

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

Note the double braces... one to indicate "this is the contents of the anonymous inner class" and one to indicate the initializer block. I wouldn't recommend this style, personally.


No. But I don't find the following code too verbose

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

Or the good old constructor calling too confusing

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

Some may suggest method chaining:

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 extra method per field. It's boiler plate code, an IDE may help here.

Then there's the builder pattern, which is even more work for the API author.

0

精彩评论

暂无评论...
验证码 换一张
取 消