saurabh agrawal
saurabh agrawal

Reputation: 131

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.

Upvotes: 9

Views: 2897

Answers (5)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Static initialisers have no business being complicated, so it's probably a bad idea (even if you don't buy SESE).

The minimal way of achieving a return is to use a labelled break.

static {
    init: {
        ...
           break init;
    }
}

They are quite rare, typically appearing in nested for loops. The novelty might tip off the reader that something a bit dodgy is going on.

Upvotes: 6

amicngh
amicngh

Reputation: 7899

You can not return from static block but better to use some other function that will perform your logic and return to the block.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718788

You cannot return from a static initializer block. There is nowhere to return to. But it shouldn't be necessary. You should be able to restructure your code to be "single entry, single exit".

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Delegate the code to a private static method:

static {
    initialize();
}

private static void initialize() {
    foo();
    if (someCondition) {
        return;
    }
    bar();
}

Upvotes: 20

Kai
Kai

Reputation: 39641

Instead of using return just wrap your conditional code in an if.

Upvotes: 7

Related Questions