jakarta-bcel-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Andrew Huntwork <...@huntwork.net>
Subject Re: Replacing inititial value of static final fields
Date Tue, 13 Dec 2005 18:06:53 GMT
static final values tend to get inlined where they are used by the
compiler.  so:

class Foo {
static final int BAR = 4;
int getBar() { return BAR; }
}

gets compiled to bytecode equivalent to

class Foo {
static final BAR = 4;
int getBar() { return 4; }
}

(specifically:
int getBar();
  Signature: ()I
  Code:
   0:   iconst_4
   1:   ireturn
)

so you're completely screwed.  there's no way to distinguish the inlined 4
from any other 4 that might have appeared literally in the source code.

On 12/13/05, Matthias Nuessler <m.nuessler@web.de> wrote:
>
> 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
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: bcel-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: bcel-user-help@jakarta.apache.org
>
>

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message