|
|
|
||
|
I have been playing around with some UI mock ups lately and it is often that I have code that looks like the following:
...
add(new Label("Some text"));
...
If I want to see what
...
add(new Label("Some text") {{ setFont(someFont); }});
...
...
add(new Label("Some text")
{
{
setFont(someFont);
}
});
...
The only question that remains is: when is the instance initializer executed? You can read section 8.8.5.1 of the JLS if you want. (The problem that I have with section 8.8.5.1 is that it is for explicit constructor invocations which doesn't seem to be the case for this example but I cannot find another reference to instance initializers in the JLS.) The code below provides a clearer answer to the question.
class PreTest {
{System.err.println("PreTest First");}
public PreTest() {
System.err.println("PreTest constructor");
}
{System.err.println("PreTest Second");}
}
class Test extends PreTest {
{System.err.println("Test First");}
public Test() {
System.err.println("Test constructor");
}
{System.err.println("Test Second");}
public Test(final int number) {
this();
System.err.println("Test constructor(" + number + ")");
}
{System.err.println("Test Third");}
public void method() {
System.err.println("Test method");
}
{System.err.println("Test Fourth");}
}
class Dummy {
public Dummy() {}
public void go(Test test) {}
}
final Dummy dummy = new Dummy();
dummy.go(new Test(10) {{ method(); }});
When executed, the following is output:
PreTest First
PreTest Second
PreTest constructor
Test First
Test Second
Test Third
Test Fourth
Test constructor
Test constructor(10)
Test method
An instance initializer is executed during construction but after all other instance initializers and all (appropriate) constructors have finished. I should point out that this "trick" is also great in unit tests for populating collections.
...
something.addList(new ArrayList() {{ add("1"); add("2"); add("3"); }});
...
foo.addMap(new HashMap() {{ put("1", "one"); put("2", "two"); }});
...
|
| Comments | ||||||||||
|
| Post a comment |
|
|
Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License. |