Filip
Filip

Reputation: 41

Java BCEL getfield instruction

Goal

I have a class A with a method called getStr. I want to replicate the code inside the method using a Instructionlist in BCEL.

public class A {
    private String str;

    private String getStr() {
        return this.str;
    }
}

Problem

I have tried the following code but with no success as it causes java.lang.NoClassDefFoundError when later running the modified class A. I think that the GETFIELD is causing this as it works without it (other instructions slightly modified).

il.append(new ALOAD(0)); // Load .this
il.append(new GETFIELD(poolGen.addFieldref("A", "str","Ljava/lang/String;"))); // Causes problem
il.append(new ARETURN()); // Return the field

MethodGen methodGen = new MethodGen(
                Constants.ACC_PRIVATE,
                Type.STRING,
                null,
                null,
                "getStr",
                "A",
                il,
                poolGen);

il.setPositions();
methodGen.setMaxLocals();
methodGen.setMaxStack();
methodGen.removeLineNumbers();

myClassGen.replaceMethod(macMethod, methodGen.getMethod());
myClassGen.update();

Question

So what is the correct way of creating a getfield instruction with BCEL?

Note: I create the private String str; field using BCEL aswell, with the code:

FieldGen fieldGen1 = new FieldGen(Constants.ACC_PRIVATE, Type.STRING, "str", poolGen);
myClassGen.addField(fieldGen1.getField());
myClassGen.update();

Upvotes: 1

Views: 262

Answers (0)

Related Questions