jdk代理模式

来源:互联网 发布:core js 编辑:程序博客网 时间:2024/06/11 15:11
package com.zhou.daili;public interface UserService {public void add();}
<pre name="code" class="java">package com.zhou.daili;public class UserServiceImpl implements UserService{public void add() {System.out.println("---------被代理的方法-----------");}}


<pre name="code" class="java">package com.zhou.daili;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class MyInvocationHandler implements InvocationHandler{/** * 目标对象 */private Object target;//构造方法传入要代理的对象public MyInvocationHandler(Object target) {super();this.target = target;}//在执行的方法前后加上逻辑public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("-----------before------------");Object result = method.invoke(target, args);System.out.println("-----------before------------");return result;}public Object getProxy(){//返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);}}


<pre name="code" class="java">package com.zhou.daili;public class ProxyTest {public static void testProxy(){UserService us = new UserServiceImpl();MyInvocationHandler handler = new MyInvocationHandler(us);UserService userService =  (UserService)handler.getProxy();userService.add();}public static void main(String[] args) {testProxy();}}



0 0
原创粉丝点击