How can we run code on an object instance before construction?

We can do it with initialization blocks. I find it actually a very interesting feature of java even though I would recommend to be very careful when using it. Indeed, initialization blocks might confuse people looking at your code especially if there is not only one and if it’s not placed close to the constructor.
So an initialization block looks like that:

{
list = new ArrayList()
}

Assuming the list member has been defined, this code will be executed just as it would have been inserted at the very beginning of the constructor.
And if there would be many of them, they would all be called in the order they appear in the class (ok, that’s even more dangerous !). Initialization blocks can also throw exceptions, as long as the constructor throws the same exceptions as well.
Now the question is: why would you use an initialization block instead of putting everything in the constructor or in a init() method like we always do. I guess, it depends. For sure, init() cannot set final members, initialization blocks can.
Also, in an anonymous inner classes, we cannot define constructors, a initialization block can play the constructor role. Code generators can also take advantage of initialization blocks, UI builders for instance.
Here is a little examples of a class with two initialization blocks and random exception.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TryItOut {

    private List list;

    {
        System.out.println("calling Hello()");
        hello();
    }

    {
        System.out.println("adding element to list");
        list.add("blabla");
        if (new Random().nextBoolean())throw new Exception("exception!");
    }

    public TryItOut() throws Exception {
        System.out.println("starting constructor, how many elements? ");
        System.out.println(list.size());
    }

    public void hello() {
        System.out.print("hello");
        list = new ArrayList();
        for (int i = 0; i < 10; i++) list.add("hello" + i);
        System.out.println(" world " + list.size());
    }

    public final static void main(String[] args) {
        try {
            new TryItOut();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Interesting, isn't it??

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>