写个HelloWorld 接口
package com.spring.aop.proxy; public interface HelloWorld { public void sayHello(); }
写个HelloWorldImpl类实现HelloWorld 接口
package com.spring.aop.proxy; public class HelloWorldImpl implements HelloWorld { public HelloWorldImpl() { System.out.println("this is HelloWorldImpl construnctor"); } @Override public void sayHello() { System.out.println("say hello HelloWorldImpl"); } }
写个工具类,执行动态代理具体操作
package com.spring.aop.proxy; import java.beans.PropertyChangeListenerProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import javax.xml.bind.Binder; public class JdkProxyExample implements InvocationHandler { private Object target = null; //获取该方法返回的代理对象 public Object bind(Object tartget) { this.target = tartget; return Proxy.newProxyInstance(tartget.getClass().getClassLoader(), tartget.getClass().getInterfaces(), this); } //invoke实现代理逻辑 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before use true object"); //反射method指代的就是代理对象实现的类 Object object = method.invoke(target, args); System.out.println("after use true object"); return object; } }
写一个测试文件
@Test void testJdkProxy() { //该对象实现InvocationHandler接口 JdkProxyExample jdkProxyExample = new JdkProxyExample(); //拿到代理对象 HelloWorld helloWorld = (HelloWorld) jdkProxyExample.bind(new HelloWorldImpl()); //因为helloWorld是一个代理对象,所以会执行invoke方法,method反射获取真正执行的方法,并通过method.invoke去执行。 helloWorld.sayHello(); }