我们如何使用 javassist 从类文件中获取常量池表?
我已经写了代码到这里:
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(filepath);
CtClass cc = pool.get(filename);
现在请告诉我进一步的步骤。
拥有 CtClass 后,您只需访问 classFile 对象即可检索常量池,如下所示:
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(filepath);
CtClass cc = pool.get(filename);
ConstPool classConstantPool = cc.getClassFile().getConstPool()
如果有人在这里绊倒,可以以更有效的方式完成(不使用 a ClassPool
):
try (InputStream inputStream = Files.newInputStream(Paths.get(filepath))) {
return new ClassFile(new DataInputStream(inputStream)).getConstPool();
}
如果性能真的很重要,可以对其进行优化,以便只从文件中读取常量池:
try (InputStream inputStream = Files.newInputStream(Paths.get(filepath))) {
return readConstantPool(new DataInputStream(inputStream));
}
在哪里:
// copied from ClassFile#read(DataInputStream)
private static ConstPool readConstantPool(@NonNull DataInputStream in) throws IOException {
int magic = in.readInt();
if (magic != 0xCAFEBABE) {
throw new IOException("bad magic number: " + Integer.toHexString(magic));
}
int minor = in.readUnsignedShort();
int major = in.readUnsignedShort();
return new ConstPool(in);
}