<dependency> <groupId>org.apache.bcel</groupId> <artifactId>bcel</artifactId> <version>6.4.1</version> </dependency> import org.apache.bcel.Constants; import org.apache.bcel.generic.*; public class DynamicClassGenerator { public static void main(String[] args) { try { generateClass(); } catch (Exception e) { e.printStackTrace(); } } public static void generateClass() throws Exception { InstructionFactory instructionFactory = new InstructionFactory(classGen); InstructionList instructionList = methodGen.getInstructionList(); instructionList.append(instructionFactory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC)); instructionList.append(new PUSH(classGen.getConstantPool(), "Hello, BCEL!")); instructionList.append(instructionFactory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[]{Type.STRING}, Constants.INVOKEVIRTUAL)); instructionList.append(InstructionFactory.createReturn(Type.VOID)); methodGen.setMaxStack(); methodGen.setMaxLocals(); classGen.addMethod(methodGen.getMethod()); JavaClass javaClass = classGen.getJavaClass(); javaClass.dump("MyClass.class"); } }


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