我们可以通过编程方式在自己的Java代码中使用javap吗?
例如,以下代码:
public class TestClass {
public static void main(String[] args) {
System.out.println("hello world");
}
}
Run Code Online (Sandbox Code Playgroud)
在命令行中使用javap,我们得到了:
// 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
}
Run Code Online (Sandbox Code Playgroud)
我可以使用javap的API仅打印常量池吗?
没有用于javap内部的API,但是您可以在package中查找javap的源代码com.sun.tools.javap。入门课程为com.sun.tools.javap.Main。所以运行javap的另一种方法是java -cp $JAVA_HOME/lib/tools.jar com.sun.tools.javap.Main YourTestClass
小智 3
Apache BCEL提供了.class文件解析的封装,它提供了一组API。几乎对于 .class 文件中的每个元素,BECL API 中都有一个对应的 Class 来表示它。因此,在某种程度上,如果您只想打印类文件的某些部分,那就不是那么简单了。这是一个简单的例子,您可以参考,注意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.
}
Run Code Online (Sandbox Code Playgroud)