Hao Hao - 6 months ago 12
Java Question

Is there an Object Initializers in Java

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",
LastName = "Doe",
Address = new Address()
{
Street = "1234 St.",
City = "Phoenix"
}
};

Answer

Actually, there is!

Person p = new Person()
{{
    setFirstName("John");
    setLastName("Doe");
    setAddress(new Address()
    {{
        setStreet("1234 St.");
        setCity("Phoenix");
    }});
}};

or even:

Person p = new Person()
{{
    firstName = "John";
    lastName = "Doe";
    address = new Address()
    {{
        street = "1234 St.";
        city = "Phoenix";
    }});
}};

This is called double brace initialization. However I would avoid this idiom as it has some unexpected side-effects, e.g. this syntax actually creates an anonymous inner class Person$1 and Address$.

See also

Comments