0

Lets say I have class Foo:

public class Foo {
    // ...
}

I want to get its constant pool as a byte array from another class. i.e:

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

Class#getConstantPool is not part of the standard API. Is there any consistent way I can get another class' constant pool?

2

2 Answers 2

2

You can get it as sun.reflect.ConstantPool object via reflection like this:

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);
        // ...
    }
}

but I'm not sure how to get it as byte array. You can try to serialize it :)

2
  • Unfortunately the interface of ConstantPool just calls native methods, so it can't be serialized.
    – konsolas
    Dec 2, 2015 at 9:47
  • Yes, you are right. What is the purpose of getting constant pool of a class? May be there is another way to achieve your goal? E.g. load .class file to byte array and use class loader after.
    – dds
    Dec 2, 2015 at 10:53
0

You can scan your class loader to find the class's location on disk, then use a framework like BCEL to analyze it.

I have a website demonstrating this, but StackOverflow says I am not allowed to post links to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.