问题
How can we get the constant pool table from the class file using javassist?
I have written the code till here:
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(filepath);
CtClass cc = pool.get(filename);
Now please, please tell me the further steps.
回答1:
Once you have the CtClass you just need to access the classFile object to retrieve the constant pool, like the following:
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(filepath);
CtClass cc = pool.get(filename);
ConstPool classConstantPool = cc.getClassFile().getConstPool()
回答2:
In case anyone stumbles here, it can be done in a more efficient way (without using a ClassPool
):
try (InputStream inputStream = Files.newInputStream(Paths.get(filepath))) {
return new ClassFile(new DataInputStream(inputStream)).getConstPool();
}
If performance is really important, it can be optimized so that only the constant pool is read from the file:
try (InputStream inputStream = Files.newInputStream(Paths.get(filepath))) {
return readConstantPool(new DataInputStream(inputStream));
}
where:
// 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);
}
来源:https://stackoverflow.com/questions/14267267/how-to-get-constant-pool-table-with-javassist