如何使用javassist获取常量池表

时间:2013-01-10 21:05:59

标签: java javassist

如何使用javassist从类文件中获取常量池表?

我已经把代码写到这里了:

ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(filepath);
CtClass cc = pool.get(filename);

现在请,请告诉我进一步的步骤。

2 个答案:

答案 0 :(得分:0)

一旦有了CtClass,你只需要访问classFile对象来检索常量池,如下所示:

ClassPool pool = ClassPool.getDefault(); 
pool.insertClassPath(filepath); 
CtClass cc = pool.get(filename);
ConstPool classConstantPool = cc.getClassFile().getConstPool()

答案 1 :(得分:0)

万一有人在这里跌跌撞撞,可以用一种更有效的方式来完成(无需使用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);
}