1:利用反射机制在运行时创建代理类
package com.wing.mall.base.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * <p> * 利用反射机制在运行时创建代理类 * </p> * * @author: heluwei * @Date: 2020/4/15 10:51 */ public class ProxyHandler implements InvocationHandler { private Object object; public ProxyHandler(Object object){ this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before invoke " + method.getName()); method.invoke(object, args); System.out.println("After invoke " + method.getName()); return null; } }
2:创建目标类
package com.wing.mall.base.proxy; public interface ByeInterface { void sayBye(); }
package com.wing.mall.base.proxy; /** * <p></p> * * @author: heluwei * @Date: 2020/4/15 10:53 */ public class Bye implements ByeInterface { @Override public void sayBye() { System.out.println("Bye 张三!"); } }
使用:
public static void main(String[] args) { Bye bye = new Bye(); InvocationHandler proxyHandler = new ProxyHandler(bye); ByeInterface byeProxy = (ByeInterface)Proxy.newProxyInstance(bye.getClass().getClassLoader(), bye.getClass().getInterfaces(), proxyHandler); byeProxy.sayBye(); }
输出: