2011-11-19 2 views
1

BCEL을 사용하여 Test 클래스의 main 메소드를 변경하려고합니다. 간단히 주()의 맨 앞에 System.out.println("This is added by BCEL at runtime") 을 추가하고 싶습니다. 예외가 발생하지 않고 InstructionList에 내 명령이 표시되지만 문자열이 인쇄되지 않고 javap -c에 수정되지 않은 버전이 표시됩니다. 내 코드는 다음과 같습니다.변경 사항을 볼 수 없습니다. BCEL

public static void main(String[] args) { 
     try { 
      JavaClass jc = Repository.lookupClass("Test"); 
      System.out.println("Found class" + jc.getClassName()); 
      ClassGen cg = new ClassGen(jc); 
      ConstantPoolGen cpg = cg.getConstantPool(); 
      for (org.apache.bcel.classfile.Method m : jc.getMethods()) { 
       if (m.getName().equals("main")) { 
        MethodGen mg = new MethodGen(m, cg.getClassName(), cpg); 
        InstructionList list = mg.getInstructionList(); 
        int stringIndex = cpg.addString("This is added by BCEL at runtime"); 
        System.out.println("String index = " + stringIndex); 
        int soutIndex = cpg.lookupFieldref("java.lang.System", "out", "Ljava/io/PrintStream;"); 
        System.out.println("Sout index = " + soutIndex); 
        int printlnIndex = cpg.lookupMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V"); 
        System.out.println("Println index = " + printlnIndex); 
        InstructionList patch = new InstructionList(); 
        patch.append(new GETSTATIC(soutIndex)); 
        patch.append(new LDC(stringIndex)); 
        patch.append(new INVOKEVIRTUAL(printlnIndex)); 
        list.insert(list.getInstructionHandles()[0], patch); 
        mg.setMaxStack(); 

        File f = new File(Repository.lookupClassFile(cg.getClassName()).getPath()); 
        cg.getJavaClass().dump(f.getPath()); 
        System.out.println(f.getPath()); 

        for (InstructionHandle ih : list.getInstructionHandles()) { 
         System.out.println(ih.getInstruction().toString()); 
        } 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

답변

0

마지막으로 실수가 있습니다. cg.replaceMethod(m, mg.getMethod());을 호출하여 변경 사항을 클래스 파일에 저장해야한다는 것을 알지 못했습니다.

관련 문제