title: Java BCEL getfield instruction
body: <p><strong>Goal</strong></p>
  
  <p>I have a class <code>A</code> with a method called <code>getStr</code>. I want to replicate the code inside the method using a <code>Instructionlist</code> in BCEL.</p>
  
  <pre><code>public class A {
      private String str;
  
      private String getStr() {
          return this.str;
      }
  }
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>I have tried the following code but with no success as it causes <code>java.lang.NoClassDefFoundError</code> when later running the modified class <code>A</code>. I think that the <code>GETFIELD</code> is causing this as it works without it (other instructions slightly modified).</p>
  
  <pre><code>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();
  </code></pre>
  
  <p><strong>Question</strong></p>
  
  <p>So what is the correct way of creating a getfield instruction with BCEL?</p>
  
  <p><strong>Note:</strong>
  I create the <code>private String str;</code> field using BCEL aswell, with the code:</p>
  
  <pre><code>FieldGen fieldGen1 = new FieldGen(Constants.ACC_PRIVATE, Type.STRING, "str", poolGen);
  myClassGen.addField(fieldGen1.getField());
  myClassGen.update();
  </code></pre>