关于常量表达式

反射那些事反射这篇文章有谈到一个常量表达式的问题,想单独拿出来研究一下。

private final int INT_VALUE=12;//常量表达式
if(a>INT_VALUE){
    //todo
}

那么java编译器会对常量表达式进行一个优化,变成如下:

if(a>12){
    //todo
}

在知乎上看到这个观点: 把常量表达式的值求出来作为常量嵌在最终生成的代码中,这种优化叫做常量折叠(constant folding)。
原来这叫做常量折叠。
简单举个例子,上面例子没有太直观。

public class ConstantTest {

    private final int a=12; //常量表达式

    private int b=12; //普通成员变量

    private final boolean flag=null==null?true:null; //非常量表达式

    public void solve(int b){
        if(b>a){
            System.out.println("yep");
        }
    }

    public void solve(){
        if(flag){
            System.out.println(b);
        }
    }

    public static void main(String[] args) {
        ConstantTest test=new ConstantTest();
        test.solve(13);
        test.solve();
    }

}

我们对ConstantTest.class文件进行反编译看看:

package com.reflect;

import java.io.PrintStream;

public class ConstantTest {
    private final int a = 12;
    private int b = 12;
    private final boolean flag = null == null ? Boolean.valueOf(true) : null;

    public void solve(int b) {
        if (b > 12) { //这里我们看到了编译器直接进行了优化,把a直接用12来进行替代。
            System.out.println("yep");
        }
    }

    public void solve() {
        if (this.flag) { //非常量表达式和普通成员变量没有发生变化
            System.out.println(this.b);
        }
    }

    public static void main(String[] args) {
        ConstantTest test = new ConstantTest();
        test.solve(13);
        test.solve();
    }

猜你喜欢

转载自www.cnblogs.com/viscu/p/9787412.html