Replacing ConstantUtf8 from ConstantPool of class using BCEL

220 Views Asked by At

I have a java class files whose constant pool consist some ConstantUtf8 data as
75. CONSTANT_Utf8 : SampleString
95. CONSTANT_Utf8 : SampleString
means same data on different index, I have written the following code:

ConstantPoolGen cp = classGen.getConstantPool();
    int a = cp.lookupUtf8("SampleString");
    if(a != -1)
    {    
        cp.setConstant(a, new ConstantUtf8("OtherString"));
        System.out.println("Found and Replaced");  
    }
    else
    {
        System.out.println("Not Found!");
    }

The above code replaces "SampleString" with "OtherString" at index 95, but I want to replace all occurrence so I have added a loop like this,

for(int i=0; i<2; i++){ 
int a = cp.lookupUtf8("SampleString");
if(a != -1)
{    
    cp.setConstant(a, new ConstantUtf8("OtherString"));
    System.out.println("Found and Replaced");  
}
else
{
    System.out.println("Not Found!");
}
}

so that it will go through both the index i.e 75 and 95 and replace with new value, but Unfortunately it producing the same result as above means only replacing one occurrence i.e at 75. What can be done to replace all?

0

There are 0 best solutions below