public static TestService createProxy1() throws Exception { // 1 创建一个类 ClassPool classPool = new ClassPool(); classPool.appendSystemPath(); CtClass proxy = classPool.makeClass("TestServiceImpl"); proxy.addInterface(classPool.get(TestService.class.getName())); // 2 创建一个方法 CtMethod sayHello = CtNewMethod.make(CtClass.voidType, "sayHello1", new CtClass[]{classPool.get(String.class.getName())}, new CtClass[0], "{System.out.println(\"hello:\" + $1);}", proxy); proxy.addMethod(sayHello); // 3 实例化类 Class aClass = classPool.toClass(proxy); return (TestService) aClass.getDeclaredConstructor().newInstance(); } static int num = 0; public static <T> T createProxy2(Class<T> classInterface, invocationHandler invocation) throws Exception { // 创建一个类 ClassPool classPool = new ClassPool(); classPool.appendSystemPath(); CtClass proxy = classPool.makeClass("proxy" + num); proxy.addInterface(classPool.get(classInterface.getName())); proxy.addField(CtField.make("public ProxyService.invocationHandler handler=null;", proxy)); for (Method method : classInterface.getMethods()) { CtClass[] parameters = Arrays.stream(method.getParameterTypes()).map(e -> { try { return classPool.get(e.getName()); } catch (NotFoundException ex) { throw new RuntimeException(ex); } }).toArray(CtClass[]::new); CtClass[] exceptions = Arrays.stream(method.getExceptionTypes()).map(e -> { try { return classPool.get(e.getName()); } catch (NotFoundException ex) { throw new RuntimeException(ex); } }).toArray(CtClass[]::new); CtClass ctClass = classPool.get(method.getReturnType().getName()); String src; if (method.getReturnType() == void.class) { src = "this.handler.invoke(\"%s\",$args);"; } else { src = "return ($r)this.handler.invoke(\"%s\",$args);"; } proxy.addMethod(CtNewMethod.make(ctClass, method.getName(), parameters, exceptions, String.format(src, method.getName()), proxy)); } Class aClass = classPool.toClass(proxy); T o = (T) aClass.getDeclaredConstructor().newInstance(); aClass.getField("handler").set(o, invocation); return o; } public static void main(String[] args) throws Exception { TestService proxy = createProxy2(TestService.class, new invocationHandler() { @Override public void invoke(String name, Object[] args) { System.out.println("hello " + Arrays.toString(args)); } }); proxy.sayHello2("111"); }
探索jdk反射思路反射工具使用
最新推荐文章于 2024-10-16 10:13:45 发布