How to use javap to see what lines of bytecode correspond to lines in the Java code?

不打扰是莪最后的温柔 提交于 2019-12-11 05:39:48

问题


I was tasked to make a method that calculates the magnitude of a given vector and then used javap -c to break it down.

Now I must show what each local variable in the magnitude frame corresponds to in the java, and which lines of bytecode correspond to what.

Here is the method I made:

public class Vector {
    /** Magnitude of vector
     * Calculates the magnitude of the vector corresponding
     *   to the array a.
     *
     * @return magnitude
     */
    public double magnitude(double[] a){
        int n = a.length;
        double sum = 1;
        for (int i=0; i<n; i++){
            sum = sum*a[i];
        }
        double magnitude = Math.sqrt(sum);
        return magnitude;
    }
}

here is the result of using javap -c:

public class Vector { 
  public Vector(); 
    Code: 
       0: aload_0 
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V 
       4: return 

  public double magnitude(double[]); 
    Code: 
       0: aload_1 
       1: arraylength 
       2: istore_2 
       3: dconst_1 
       4: dstore_3 
       5: iconst_0 
       6: istore        5 
       8: iload         5 
      10: iload_2 
      11: if_icmpge     27 
      14: dload_3 
      15: aload_1 
      16: iload         5 
      18: daload 
      19: dmul 
      20: dstore_3 
      21: iinc          5, 1 
      24: goto          8 
      27: dload_3 
      28: invokestatic  #2                  // Method java/lang/Math.sqrt:(D)D 
      31: dstore        5 
      33: dload         5 
      35: dreturn 
}

回答1:


Run javap with the -l flag:

$ javap -c -l Vector

Compiled from "Vector.java"
public class Vector {
  public Vector();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        
    LineNumberTable:
      line 1: 0

  public double magnitude(double[]);
    Code:
       0: aload_1       
       1: arraylength   
       2: istore_2      
       3: dconst_1      
       4: dstore_3      
       ...
      35: dreturn       
    LineNumberTable:
      line 12: 0
      line 14: 3
      line 16: 5
      line 18: 14
      line 16: 21
      line 22: 27
      line 24: 33
}

For example, you can see that instructions 3 & 4 correspond to line 14, where 1 is loaded into a double at index 2.



来源:https://stackoverflow.com/questions/26870826/how-to-use-javap-to-see-what-lines-of-bytecode-correspond-to-lines-in-the-java-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!