javac根据赋值方法区别对待静态final [英] javac treating static final differently based on assignment method

查看:26
本文介绍了javac根据赋值方法区别对待静态final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译时:

public static final boolean FOO = false;
public static final void fooTest() {
    if (FOO) {
        System.out.println("gg");
    }
}

我得到一个空方法 fooTest() {}.但是当我编译时:

I get an empty method fooTest() {}. However when I compile:

static boolean isBar = false;
public static final boolean BAR = isBar;
public static final void fooTest() {
    if (BAR) {
        System.out.println("gg");
    }
}

if 语句包含在已编译的类文件中.这是否意味着java中有两种不同的静态final类型",或者这只是编译器优化?

the if statement is included in the compiled class file. Does this mean there are two different "types" of static final in java, or is this just a compiler optimization?

推荐答案

在第一种情况下,编译器会进行优化.它知道 Foo 将永远是 false 并杀死永远不会到达的代码.

In the first case, the compiler does an optimization. It knows Foo will always be false and kill the code than will never be reached.

在第二种情况下,您将非最终变量 isBar 的值分配给 BAR.编译器无法判断变量 isBar 是否在其他地方被修改,特别是如果它不是私有的.因此不确定BAR 的值.因此他不能做优化.

In the second case, you are assigning the value of the non-final variable isBar to BAR. The compiler can't tell if the variable isBar has been modified somewhere else, especially if it is not private. Therefore it is not sure of the value of BAR. Therefore he can not do the optimization.

这篇关于javac根据赋值方法区别对待静态final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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