Question

How do I rename things using BCEL? So far what I do is go through each method in a class and create a new NameAndType constant in the constant pool, then I replace the old NameAndType constant with that one

int nameRef = cpg.addNameAndType(newName, m.getSignature());
cpg.setConstant(m.getNameIndex(), cpg.getConstant(nameRef));

This seems like it should work but my decompiler tells me the constant pool is corrupt after this. Am I missing a step or something?

Was it helpful?

Solution

You're assuming that the ConstantPoolGen is just a table of indices and values. But I believe that actually, it has a much more complicated internal structure. Looking at the ConstantPoolGen method, it is clear that it also holds references to MethodGen objects which may or not me updated when you run your code.

I advise you not to manipulate the Constant Pool directly, but to get each method of the class (as a MethodGen object), and use the method setName(). The constant pool will be updated automatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top