在静态初始化器中返回 [英] Returning in a static initializer

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

问题描述

这不是有效的代码:

public class MyClass
{
    private static boolean yesNo = false;

    static
    {
        if (yesNo)
        {
            System.out.println("Yes");
            return; // The return statement is the problem
        }
        System.exit(0);
    }
}

这是一个愚蠢的例子,但在静态类中构造函数我们不能 return;
为什么?这有充分的理由吗?有人知道更多关于此的事情吗?

This is a stupid example, but in a static class constructor we can't return;. Why? Are there good reasons for this? Does someone know something more about this?

所以我应该做 return 的原因是结束那里的构建。

So the reason why I should do return is to end constructing there.

谢谢

推荐答案

我认为原因是初始化器被携带与字段初始化(以及构造函数,在实例初始化程序的情况下)一起使用。换句话说,JVM只识别一个地方来初始化静态字段,因此所有初始化 - 无论是否在块中 - 必须在那里完成。

I think the reason is that initializers are carried together with field initializations (and with constructors, in the case of instance initializers). In other words, the JVM only recognizes one place to initialize static fields, and thus all initializations - whether in blocks or not - must be done there.

所以,例如,当你写一个班级时:

So, for example, when you write a class:

class A {
    static int x = 3;
    static {
        y = x * x;
    }
    static int z = x * x;
}

然后它实际上就像你写的那样:

Then it's actually as if you've written:

class A {
    static int x, y, z;
    static {
        x = 3;
        y = x * x;
        z = x * x;
    }
}

如果您查看反汇编,则会确认:

This is confirmed if you look at the disassembly:

static {};
  Code:
   0:   iconst_3
   1:   putstatic       #5; //Field x:I
   4:   getstatic       #5; //Field x:I
   7:   getstatic       #5; //Field x:I
   10:  imul
   11:  putstatic       #3; //Field y:I
   14:  getstatic       #5; //Field x:I
   17:  getstatic       #5; //Field x:I
   20:  imul
   21:  putstatic       #6; //Field z:I
   24:  return

所以如果你想添加一个返回在静态初始化器中间的某处,它也会阻止z被计算。

So if you would have added a "return" somewhere in the middle of your static initializer it would also have prevented z from being calculated.

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

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