import org.apache.bcel.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; import org.apache.bcel.util.*; public class BCELExample { public static void main(String[] args) { try { JavaClass javaClass = Repository.lookupClass("com.example.MyClass"); ClassGen classGen = new ClassGen(javaClass); ConstantPoolGen constantPoolGen = classGen.getConstantPool(); int newStringIndex = constantPoolGen.addString("Hello BCEL"); Method mainMethod = javaClass.getMethod("main", "([Ljava/lang/String;)V"); MethodGen methodGen = new MethodGen(mainMethod, javaClass.getClassName(), constantPoolGen); InstructionList instructionList = methodGen.getInstructionList(); instructionList.append(new PUSH(constantPoolGen, newStringIndex)); instructionList.append(new INVOKESTATIC(constantPoolGen.addMethodref("java/lang/System", "out", "(Ljava/lang/String;)V"))); methodGen.setInstructionList(instructionList); methodGen.setMaxStack(); methodGen.setMaxLocals(); classGen.replaceMethod(mainMethod, methodGen.getMethod()); JavaClass modifiedClass = classGen.getJavaClass(); modifiedClass.dump("MyClass_modified.class"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文