9

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.

3
  • 3
    please provide your source code Commented Jun 20, 2012 at 11:08
  • I can't understand the problem. Please explain it clearly or provide your code for easy understanding. Commented Jun 20, 2012 at 11:11
  • 2
    @Kalai I suppose he means that return can not be used within an initializer block. JLS 14.17: "[...] It is a compile-time error if a return statement is contained in an instance initializer or a static initializer [...]" Commented Jun 20, 2012 at 11:24

5 Answers 5

20

Delegate the code to a private static method:

static {
    initialize();
}

private static void initialize() {
    foo();
    if (someCondition) {
        return;
    }
    bar();
}
Sign up to request clarification or add additional context in comments.

3 Comments

cleaner way to write inialize blocks.
can't assign static final field this way
@wilmol Sure you can :) Either use private static final Singleton INSTANCE = initialize(); or static { INSTANCE = initialize(); }.
7

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

Comments

6

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.

Comments

0

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".

1 Comment

I would have to agree with this statement, it would also provide much cleaner (and easier to read) code.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.