Search code examples
javabytecodebytecode-manipulationbcel

How to change value of a static field using BCEL?


I want to reset a static field using BCEL, for instance

private static final int myValue = 1;

to myValue = 2. Using another bytecode library such as ASM is not possible.


Solution

  • The code in my question: Injecting code in an existing method using BCEL used to edit a static array. I however later changed it to edit a local variable. The code to edit a static variable was something like this:

    InstructionList il = new InstructionList();
    InstructionFactory f = new InstructionFactory(constantPoolGen);
    il.append(f.createGetStatic("MyClassName","MyVariableName",Type.INT));
    il.append(new PUSH(contantPoolGen, 2));
    il.append(new ISTORE());
    

    The InstructionList I used got injected in a method so i'm not sure if that works for you..