如何从java中的静态初始化块返回 [英] How to return from a static initialization block in java

查看:143
本文介绍了如何从java中的静态初始化块返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从静态块返回。

看起来return和break语句不起作用。有没有其他选择。

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.

推荐答案

将代码委托给私有静态方法:

Delegate the code to a private static method:

static {
    initialize();
}

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

这篇关于如何从java中的静态初始化块返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆