Returning in a static initializer(返回静态初始化器)
问题描述
这不是有效的代码:
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.
这篇关于返回静态初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回静态初始化器
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01