Reputation: 131
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
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
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
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
Reputation: 691715
Delegate the code to a private static method:
static {
initialize();
}
private static void initialize() {
foo();
if (someCondition) {
return;
}
bar();
}
Upvotes: 20