How to return from a static initialization block i

2019-02-21 21:02发布

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.

5条回答
Animai°情兽
2楼-- · 2019-02-21 21:12

Delegate the code to a private static method:

static {
    initialize();
}

private static void initialize() {
    foo();
    if (someCondition) {
        return;
    }
    bar();
}
查看更多
家丑人穷心不美
3楼-- · 2019-02-21 21:13

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

查看更多
小情绪 Triste *
4楼-- · 2019-02-21 21:23

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

查看更多
来,给爷笑一个
5楼-- · 2019-02-21 21:27

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

查看更多
ゆ 、 Hurt°
6楼-- · 2019-02-21 21:37

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.

查看更多
登录 后发表回答