title: how to change field‘s initial value using javassist
body: <p>I'm trying to mock some services in my developing env. The serviceFactory code is something like:</p>
  
  <pre><code>public class ApiFacadeImpl implements ApiFacade {
  private OneService oneService = null;
      public OneService getOneService(){
          if(oneService==null) {//some initialization steps }
          return oneService;
      }
  }
  </code></pre>
  
  <p>I know this factory is not well coded and designed. However I can't modify its code.
  my idea is to change the bytecode, so I can redefine it to something like:</p>
  
  <pre><code>public class ApiFacadeImpl implements ApiFacade {
  private OneService oneService = new MyMockOneService();
      ....
  }
  </code></pre>
  
  <p><strong>My 1st is:
  is this possible using javassist?  And how?</strong></p>
  
  <p>Since I can't find anything like reinitialize a field using javassist using google, I tried myself by deleting it and recreate it:</p>
  
  <pre><code>        CtField oneServiceField = cc.getDeclaredField("oneService");
      cc.removeField(oneServiceField);
      CtField f = CtField.make(String.format("private %s %s=new %s();",
              oneServiceField.getType().getName(), "oneService",
              mockClass.getCanonicalName()), cc);
      cc.addField(f);
      cc.toClass();
  </code></pre>
  
  <p>then I got exception:</p>
  
  <pre><code>javassist.CannotCompileException: by java.lang.ClassFormatError: Invalid length 99 in LocalVariableTable in class file com/Test
  at javassist.ClassPool.toClass(ClassPool.java:1051)
  at javassist.ClassPool.toClass(ClassPool.java:994)
  at javassist.ClassPool.toClass(ClassPool.java:952)
  at javassist.CtClass.toClass(CtClass.java:1079)
  </code></pre>
  
  <p><strong>My 2nd question is why this exception? Which step disobey java class's definition? And when I delete the field does javassist help to delete field reference in:</strong></p>
  
  <pre><code>public OneService getOneService(){
          if(oneService==null) {//some initialization steps }
          return oneService;
      }
  </code></pre>
  
  <p>Many thanks.</p>