public interface HelloService { void sayHello(String name); } import org.apache.bcel.*; import org.apache.bcel.generic.*; public class ProxyGenerator { public static void main(String[] args) throws Exception { ConstantPoolGen constantPoolGen = classGen.getConstantPool(); classGen.addInterface("HelloService"); FieldGen fieldGen = new FieldGen(Const.ACC_PRIVATE, new ObjectType("HelloService"), "helloService", constantPoolGen); classGen.addField(fieldGen.getField()); InstructionList il = new InstructionList(); il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); il.append(InstructionFactory.createInvoke("java.lang.Object", "<init>", Type.VOID, new Type[] {}, Const.INVOKESPECIAL)); il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); il.append(InstructionFactory.createLoad(new ObjectType("HelloService"), 1)); il.append(InstructionFactory.createPutField("DynamicProxy", "helloService", new ObjectType("HelloService"))); il.append(InstructionFactory.createReturn(Type.VOID)); MethodGen methodGen = new MethodGen(Const.ACC_PUBLIC, Type.VOID, new Type[] { new ObjectType("HelloService") }, new String[] { "helloService" }, "<init>", "DynamicProxy", il, constantPoolGen); methodGen.setMaxStack(2); methodGen.setMaxLocals(); classGen.addMethod(methodGen.getMethod()); il = new InstructionList(); il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); il.append(InstructionFactory.createGetField("DynamicProxy", "helloService", new ObjectType("HelloService"))); il.append(InstructionFactory.createLoad(Type.OBJECT, 1)); il.append(InstructionFactory.createInvoke("HelloService", "sayHello", Type.VOID, new Type[] { Type.STRING }, Const.INVOKEINTERFACE)); il.append(InstructionFactory.createReturn(Type.VOID)); classGen.addMethod(new MethodGen(Const.ACC_PUBLIC, Type.VOID, new Type[] { Type.STRING }, new String[] { "name" }, "sayHello", "DynamicProxy", il, constantPoolGen).getMethod()); JavaClass javaClass = classGen.getJavaClass(); javaClass.dump("DynamicProxy.class"); } }


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