以编程方式获取类的常量池

时间:2015-11-29 10:03:34

标签: java

假设我有Foo课程:

public class Foo {
    // ...
}

我希望将其常量池作为另一个类的字节数组。即:

public class Bar {
    void butts() {
        byte[] fooConstantPool = Foo.class.getConstantPool();
        // ...
    }
}

Class#getConstantPool不是标准API的一部分。有没有一致的方法我可以获得另一个类的恒定池?

2 个答案:

答案 0 :(得分:0)

您可以通过这样的反射将其作为sun.reflect.ConstantPool对象获取:

import sun.reflect.ConstantPool;
public class Bar {
    private static final Method getConstantPool;

    static {
        try {
            getConstantPool = Class.class.getDeclaredMethod("getConstantPool");
            getConstantPool.setAccessible(true);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
    void butts() {
        ConstantPool constantPool = (ConstantPool) getConstantPool.invoke(Foo.class);
        // ...
    }
}

但我不确定如何将其作为字节数组。您可以尝试序列化它:)

答案 1 :(得分:0)

您可以扫描类加载器以在磁盘上查找类的位置,然后使用类似BCEL的框架来分析它。

我有一个网站证明了这一点,但StackOverflow说我不允许发布链接。

相关问题