5

Can we use javap in our own java code in a programmable way?

for example, the following code:

public class TestClass {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
}

using javap in command line, we got :

// Header + consts 1..22 snipped
const #22 = String      #23;    //  hello world
const #23 = Asciz       hello world;

public static void main(java.lang.String[]);
  Signature: ([Ljava/lang/String;)V
  Code:
   Stack=2, Locals=1, Args_size=1
   0:   getstatic       #16; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc     #22; //String hello world
   5:   invokevirtual   #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8:   return
  // Debug info snipped
}

can I print only the Constant Pool using javap's API?

DON1101
  • 83
  • 3
  • This is a good chance to learn about class file structure. – xiaofeng.li Jan 21 '13 at 07:48
  • But I just want to retrieve some part of the class file instead of the whole structure, such as the constant pool only, for my own purpose. Do you have any clues? – DON1101 Jan 22 '13 at 02:58
  • See [this class file parser](https://docs.google.com/folder/d/0B0LIJo-NJZ-UX0Q4eGV6b01JTk0/edit) – Hot Licks Jan 22 '13 at 03:27

2 Answers2

6

There is no API for javap internals, but you can look for the source code of javap, which is in the package com.sun.tools.javap. The entry class is com.sun.tools.javap.Main. So another way to run javap is java -cp $JAVA_HOME/lib/tools.jar com.sun.tools.javap.Main YourTestClass

Wu Yongzheng
  • 1,707
  • 17
  • 23
  • Very nice solution for cases where not much functionality is needed – Daniel Alder Apr 12 '14 at 12:52
  • This helped me a lot parsing method signatures without having all dependencies of the class file! Because reflection with `Class.forName(...)` wants to have all dependencies at runtime. – bobbel Aug 03 '16 at 08:26
3

Apache BCEL provides encapsulations of .class file parsing, which provides a set of API. Almost for every element in .class file, there's a corresponding Class in BECL API to represent it. So in some way, it is not that straightforward if you just want to print out certain sections of the class file. Here is a simple example you can refer, pay attention to the org.apache.bcel.classfile.ClassParser:

    ClassParser cp = new ClassParser("TestClass.class");
    JavaClass jc = cp.parse();
    ConstantPool constantPool = jc.getConstantPool(); // Get the constant pool here.
    for (Constant c : constantPool.getConstantPool()) {
        System.out.println(c); // Do what you need to do with all the constants.
    }
Gavin Xiong
  • 957
  • 6
  • 9