简体   繁体   English

Java ByteCode算术运算

[英]Java ByteCode arithmetic operation

I'm going to make a simple compiler for a school project, i want generate .class file, i read the file format but to understand better the .class file format and the java bytecode i have this class: 我将为学校项目制作一个简单的编译器,我想生成.class文件,我读取了文件格式,但是为了更好地理解.class文件格式和java字节码,我有这个类:

public class Me {
    public void myMethod() {
        int a = 5 * 4 + 3 - 2 + 1 / 7 + 28;
    }
}

with javap command i get this(for 'myMethod'): 用javap命令我得到这个(对于'myMethod'):

public void myMethod();
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=1
         0: bipush        49
         2: istore_1      
         3: return        
      LineNumberTable:
        line 3: 0
        line 4: 3
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       4     0  this   LMe;
               3       1     1     a   I

In this line: 在这一行:

 0: bipush        49

I dont understand when we get that number(49), i dont see the byte code for the arithmetic operation '5 * 4 + 3 ...' 我不明白何时获得该数字(49),我看不到算术运算“ 5 * 4 + 3 ...”的字节码

I dont understand when we get that number(49), i dont see the byte code for the arithmetic operation '5 * 4 + 3 我不明白何时获得该数字(49),我看不到算术运算'5 * 4 + 3的字节码

The bytecode compiler is optimizing them away. 字节码编译器正在优化它们。 The expression is a constant expression according to the JLS definition, and that means that the java compiler is permitted to evaluate it at compile time and hard-code the resulting value into the class file. 该表达式是根据JLS定义的常量表达式 ,这意味着允许java编译器在编译时对其进行评估,并将结果值硬编码到类文件中。

If you want to see what the bytecodes for expression evaluation look like, you need to use parameters, local variables, etc as the "primaries" in the expression; 如果要查看表达式评估的字节码是什么样的,则需要使用参数,局部变量等作为表达式中的“主要”; eg 例如

public int myMethod(int a, int b, int c) {
    return a + b * c / 42;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM