Search code examples
javaclassbytecode

output a list of all the methods, and the number of bytes in a java class file?


I want to know how to get the list of all the methods and the number of bytes for each method in a class file.

For example :

I want to have a main source code where it can parse few .class files through cmd line arguments and get the above mentioned details of each classes.

    javac myapp classFile1.class classFile2.class ... 

Please Note : I know the list of method can be taken through javap className.class


Solution

  • As this is a homework assignment, the particular constraints of your class are important. For example, are you allowed to use libraries or are you expected to write your own classfile parser? If the later, then you just need to read the JVM specification and write a parser for it.

    Assuming you are allowed to use libraries, I'd recommend using Objectweb ASM. This will save you from dealing with low level details of the classfile format and having to write a parser.

    Looking at ClassReader.java, the size of the bytecode is not directly exposed to client code. However, readLabel is always called with codeLength + 1 at the beginning of readCode. Therefore, if you subclass ClassReader and override readLabel, you can get the length of the bytecode for each method.

    You'll also want to create a MethodVistor and override visitMethodInsn to get the invoke instructions required for the later parts of the assignment.