静态块在编译后的结构发生变化

huangapple go评论84阅读模式
英文:

Static block structure changing after compilation

问题

我在静态块之后声明了一个静态变量。当我调用一个方法来打印它的值时,结果是0。我反编译了.class文件并发现静态块的结构已经改变了。有人能解释一下为什么吗?

class Testing {
static {
    callMe();
    System.out.println("Static finished");
}
static void callMe() {
    System.out.println(x);
}
static int x = 10;
public static void main(String[] args) {
    System.out.println("Complete");
}}

反编译后的代码:

class Testing {
static int x;

Testing() {
}

static void callMe() {
    System.out.println(x);
}

public static void main(String[] args) {
    System.out.println("Complete");
}

static {
    callMe();
    System.out.println("Static finished");
    x = 10;
}}
英文:

I'm declaring a static variable after static block. When I'm calling a method to print its value, the result is 0. I decompiled the .class file and found that the structure of the static block has changed. Can anyone please explain why?

class Testing {
static {
    callMe();
    System.out.println("Static finished");
}
static void callMe() {
    System.out.println(x);
}
static int x = 10;
public static void main(String[] args) {
    System.out.println("Complete");
}}

Decompiled code :

class Testing {
static int x;

Testing() {
}

static void callMe() {
    System.out.println(x);
}

public static void main(String[] args) {
    System.out.println("Complete");
}

static {
    callMe();
    System.out.println("Static finished");
    x = 10;
}}

答案1

得分: 1

编译器可以重新排序执行,如果总体结果相同。

在您的情况下是这样的,因为static块和初始化程序是按照声明顺序执行的,所以static int x = 10;的内联赋值在打印之后执行。

至于为什么您的确切编译器版本会以其所做的方式重新排序代码,这是一个问题,应该向编译器开发团队提问。

英文:

The compiler is allowed to reorder execution if the overall result is the same.

In your case this is so, because static blocks and initializers are executed in declared order, so the in-line assignment of static int x = 10; is executed after the print.

As for why your exact compiler version reordered your code the way it did is a question for the compiler dev team.

huangapple
  • 本文由 发表于 2020年8月30日 04:54:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63651706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定