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.
这篇关于返回静态初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回静态初始化器
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01