Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return from a static initialization block in java

I want to return from the static block.

Looks like the return and break statement don't work. Is there any alternative.

I know the bad workaround could be create a flag and check the flag to continue or not.

I understand that the initialisation blocks are not meant for doing computations but just for basic initialisation during class loading.

like image 648
saurabh agrawal Avatar asked Jun 20 '12 11:06

saurabh agrawal


1 Answers

Delegate the code to a private static method:

static {
    initialize();
}

private static void initialize() {
    foo();
    if (someCondition) {
        return;
    }
    bar();
}
like image 153
JB Nizet Avatar answered Oct 04 '22 20:10

JB Nizet