如何使用javassist获取常量池表

问题描述 投票:1回答:2

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

我写代码直到这里:

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

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

java javassist
2个回答
0
投票

获得CtClass之后,您只需要访问classFile对象以检索常量池,如下所示:

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.