【问题标题】:How to use javap to see what lines of bytecode correspond to lines in the Java code?如何使用javap查看Java代码中的哪些字节码行对应了哪些行?
【发布时间】:2014-11-11 17:30:02
【问题描述】:

我的任务是创建一种方法来计算给定向量的大小,然后使用javap -c 将其分解。

现在我必须显示幅度帧中的每个局部变量在java中对应什么,以及哪些字节码对应什么。

这是我做的方法:

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;
    }
}

这是使用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 
}

【问题讨论】:

    标签: java javap


    【解决方案1】:

    使用-l 标志运行javap

    $ 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
    }
    

    例如,您可以看到指令 3 和 4 对应于第 14 行,其中 1 被加载到索引 2 处的 double 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多