Can C# style object initialization be used in Java?
Asked Answered
I

4

28

In C# it's possible to write:

MyClass obj = new MyClass()
{
    field1 = "hello",
    field2 = "world",
    field3 = new MyOtherClass()
    {
        etc....
    }
}

I can see that array initialization can be done in a similar way but can something similar to the above be done in Java too, and if so, what's the syntax?

Infix answered 12/7, 2011 at 17:8 Comment(0)
B
43

That initialization syntax is not present in Java.

A similar approach is to use double brace initialization, where you create an anonymous inner sub class with an initializer block:

MyClass obj = new MyClass() {{
  // in Java these would be more like this: setFieldX(value);
  field1 = "hello";
  field2 = "world";
  field3 = new MyOtherClass() ...
}};

Be aware though, that you're actually creating a subclass.

Another approach is to create a builder for MyClass, and have code like this:

MyClass obj = new MyClassBuilder().
  withField1("hello").
  withField2("world").
  withField3(new MyOtherClass()).
  build();
Burdensome answered 12/7, 2011 at 17:14 Comment(3)
There is a useful Eclipse plugin for generating builders, though is not maintained any more code.google.com/p/fluent-builders-generator-eclipse-pluginMargetts
sooooo.... to get the easy instantiation syntax, I need to write a new Builder class? For every type? no thanks.Bendwise
@Cheeso: you're right of course, it's really heavyweight to use this pattern for every class, and there's no need to do it really. It's a balance between author effort and consumer convenience, and I'm sure not every class would need to use it. Joshua Bloch gives some advice of when it might be useful.Ocrea
R
2

Java does not have the capability built in to instantiate an object using the shorter syntax. The C# compiler handles this and separates out the property setters in the IL. Until the Java langauge devs decide this is important, you will not be able to take this shortcut.

Roose answered 12/7, 2011 at 17:19 Comment(0)
V
2

Just create constructors for initialization.

MyClass obj = new MyClass()
{
    field1 = "hello",
    field2 = "world",
    field3 = new MyOtherClass()
    {
        etc....
    }

    public MyClass()
    {
        initialize();
    }

    public MyClass(String field1)
    {
        this.field1 = field1;
        this();
    }

    public MyClass(String field, Boolean isField1)
    {
        if (isField1)
            this( field );
        else
            this.field2 = field;

        this();
    }

    public MyClass(String field1, String field2)
    {
        this.field2 = field2;
        this(field1);
    }

    public MyClass(MyOtherClass field3)
    {
        this.field3 = field3;
    }

    public MyClass(String field1, String field2, MyOtherClass field3)
    {
        this(field3);
        this(field1, field2);
    }

    private void initialize(){
        // Do any class bootstrapping here.
    }
}

// Then you have several ways to create an object instance, with initialization
MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass( "Field 1 Value" );
MyClass myClass3 = new MyClass( "Field 1 Value", true );
MyClass myClass4 = new MyClass( "Field 2 Value", false );
MyClass myClass5 = new MyClass( "Field 1 Value", "Field 2 Value" );
MyClass myClass6 = new MyClass( "Field 1 Value", "Field 2 Value", new MyOtherClass() );
MyClass myClass7 = new MyClass( new MyOtherClass() );
Velez answered 5/6, 2013 at 16:57 Comment(1)
Just huh? This is the correct answer but indicative of a fundamental wrongness.Melise
T
0

If you're willing to use fancy tools, reach for Lombok's Builder feature: https://projectlombok.org/features/Builder

@Builder    // <-- Magic!
public class MyClass {
    private String field1;
    private int field2;
    private SomeObj field3;
}

...

var myObj = MyClass.builder()
    .field1("Hello")
    .field2(3)
    .field3(SomeObj.builder()
        .someProp1(...)
        .someProp2(...)
        .build()
    ).build();

Tuberculosis answered 5/4 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.