import org.apache.bcel.Const; import org.apache.bcel.generic.*; public class BCELExample { public static void main(String[] args) { MethodGen constructor = new MethodGen(Const.ACC_PUBLIC, Type.VOID, new Type[]{}, new String[]{}, "<init>", "ExampleClass", new InstructionList(), classGen.getConstantPool()); InstructionFactory factory = new InstructionFactory(classGen); InstructionList instructions = new InstructionList(); instructions.append(factory.createReturn(Type.VOID)); constructor.setInstructionList(instructions); constructor.setMaxStack(); constructor.setMaxLocals(); classGen.addMethod(constructor.getMethod()); instructions = new InstructionList(); instructions.append(factory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Const.GETSTATIC)); instructions.append(new PUSH(classGen.getConstantPool(), "Hello, BCEL!")); instructions.append(factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[]{Type.STRING}, Const.INVOKEVIRTUAL)); instructions.append(factory.createReturn(Type.VOID)); mainMethod.setInstructionList(instructions); mainMethod.setMaxStack(); mainMethod.setMaxLocals(); classGen.addMethod(mainMethod.getMethod()); JavaClass javaClass = classGen.getJavaClass(); javaClass.dump("ExampleClass.class"); } }


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