How to get constant pool table with javassist

老子叫甜甜 提交于 2019-12-11 10:52:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!