Java 中是否有类似于 C# 中的对象创建表达式?
在 C# 中,我可以创建我编写的每个自定义类的实例,并为其成员传递值,如下所示:
public class MyClass
{
public int number;
public string text;
}
var newInstance = new MyClass { number = 1, text = "some text" };
这种创建对象的方式称为 对象创建表达式。有没有办法在 Java 中做同样的事情?我想为类的任意公共成员传递值。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有什么直接相似的。在 Java 中(无需编写构建器类等)最接近的方法是使用匿名内部类和初始化块,这很糟糕,但有效:
注意双大括号...一个表示“这是匿名内部类的内容”内部类”和一个表示初始化块。我个人不会推荐这种风格。
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:
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.
不。但我不认为下面的代码太冗长
,或者旧的构造函数调用太混乱。
有些人可能建议方法链接:
每个字段需要一个额外的方法。这是样板代码,IDE 可能会有所帮助。
然后是构建器模式,这对于 API 作者来说是更多的工作。
No. But I don't find the following code too verbose
Or the good old constructor calling too confusing
Some may suggest method chaining:
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.