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

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

问题描述

这不是有效的代码:

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天全站免登陆