How to return from static initialization block in java

I want to return from a static block.

The return and break statement does not seem to work. Is there an alternative.

I know that the wrong workaround can create a flag and check the flag to continue or not.

I understand that initialization blocks are not designed to perform calculations, but simply for basic initialization during class loading.

+7
source share
5 answers

Pass the code to the private static method:

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

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

+7
source

Static initializers do not have a complicated business, so this is probably a bad idea (even if you are not buying SESE).

The minimum way to achieve a return is to use a marked break.

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

They are quite rare, usually appearing in nested for loops. The novelty may overturn the reader that something a little quirky is happening.

+1
source

You cannot return from a static initializer block. Nowhere to return. But this is optional. You should be able to restructure your code as a "single entry, one exit."

0
source

You cannot return from a static block, but it is better to use another function that will execute your logic and return to the block.

0
source

All Articles