Are C# style object initializers available in Java

后端 未结 3 1941
情话喂你
情话喂你 2020-12-24 10:46

Like this one? http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx

Person p = new Person()
{
    FirstName = \"John\",
         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 10:53

    Others have shown the "double brace" initializers, which I think should be avoided - this isn't what inheritance is for, and it will only work as shown when the fields are directly visible to subclasses, which I'd also argue against. It's not really the same thing as C# initializer blocks. It's a hack to take advantage of a language feature designed for other purposes.

    If you have more values than you wish to pass to a constructor, you might want to consider using the builder pattern:

    Person person = Person.newBuilder()
        .setFirstName("John")
        .setLastName("Doe")
        .setAddress(Address.newBuilder()
            .setStreet("...")
            .setCity("Phoenix")
            .build())
        .build();
    

    This also allows you to make Person immutable. On the other hand, doing this requires the Person class to be designed for this purpose. That's nice for autogenerated classes (it's the pattern that Protocol Buffers follows) but is annoying boiler-plate for manually-written code.

提交回复
热议问题