Replacing inititial value of static final fields
Matthias Nuessler <[email protected]> Tue, 13 Dec 2005 18:40:22 +0100
| Newsgroups | gmane.comp.jakarta.bcel.user |
|---|---|
| Organization | http://freemail.web.de/ |
| Message-ID | <[email protected]> |
Hi,
I was trying to use BCEL to replace the initial value of static final fields of existing classes. It seemed to work fine, but when the fields are referenced from other classes they seem to contain the old values, eventhough the values in the changed class itself are updated to the new value. Is there any way using BCEL to change these constant values in that way? Maybe I'm not aware of certain problems regarding the constant pool?
Here is what I did. Let's say, in a class named "Hello" I have a field like this:
public static final String MESSAGE = "Hello";
Now I want to read in the class file and change the initial value:
ClassParser parser = new ClassParser("Hello.class");
JavaClass javaClass = parser.parse();
ClassGen cg = new ClassGen(javaClass);
ConstantPool cp = javaClass.getConstantPool();
ConstantPoolGen pg = new ConstantPoolGen(cp);
Field[] fields = classGen.getFields();
for (int i=0; i<fields.length; i++) {
if (fields[i].getName().equals("MESSAGE")) {
FieldGen fg = new FieldGen(ACC_PUBLIC | ACC_STATIC | ACC_FINAL, Type.STRING, "MESSAGE", pg)
fg.setInitialValue("New Message");
cg.removeField(fields[i]);
cg.addField(fg.getFielD());
}
}
JavaClass changedClass = cg.getJavaClass();
changedClass.setConstantPool(pg.getFinalConstantPool());
changedClass.dump("Hello_.class");
Thanks
Matt
______________________________________________________________
Verschicken Sie romantische, coole und witzige Bilder per SMS!
Jetzt bei WEB.DE FreeMail: http://f.web.de/?mc=021193