How can I measure number of bytecode instructions

2019-07-07 08:15发布

问题:

I have calculated the average cyclomatic complexity for each of my class files. I was wondering how I could measure the number of bytecode instructions in each of my class files using Eclipse perhaps?

回答1:

I don't know if you can do that easily from Eclipse, but you can use javap -c to get a disassembly of your class files. Shouldn't be too hard to wrap that in a script if you only care about the number of instructions per method.

Example:

 $ javap -c Test
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc #3; //String Hello
   5:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8:   return

}


回答2:

Use javap as mentioned by Mat, ore use Commons BCEL to access the byte code programmatically.