动态代理

1.  接口类

package com.dynamicProxy;

public interface User {
    int add(int i, int j);
    int sub(int i, int j);
    int mul(int i, int j);
    int div(int i, int j);
}

2. 实现类

package com.dynamicProxy;

public class UserImpl implements User {

    public int add(int i, int j) {
        return i + j;
    }

    public int sub(int i, int j) {
        return i - j;
    }

    public int mul(int i, int j) {
        return i*j;
    }

    public int div(int i, int j) {
        return i/j;
    }

}

3. 代理类

package com.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.rmi.server.LoaderHandler;
import java.util.Arrays;

public class UserImplProxy {
    //1. 指定被代理的对象
    private User u = null;
    
    //2. 传入被代理的对象
    public UserImplProxy(User u) {
        this.u = u;
    }
    
    //3. 定义一个返回 User 对象的方法
    public User getProxyObject() {
        User userProxy = null;
        
        //5. 对象由那个类加载器负责
        ClassLoader loader = u.getClass().getClassLoader();
        
        //6. 代理对象的类型,  即那些方法
        Class[] interfaces = new Class[] {User.class};
        
        //7. 当调用代理对象的方法时   执行其中的方法
        InvocationHandler h = new InvocationHandler() {
            /**
             * proxy: 正在返回的那个代理对象
             * method: 代理对象执行的方法
             * args: 执行参数
             */
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("The method "+method.getName()+" begin with "+Arrays.asList(args));
                Object result = method.invoke(u, args);
                return result;
            }
        };
        
        //4. 通过代理方法来处理 User 对象的方法
        userProxy = (User) Proxy.newProxyInstance(loader, interfaces, h);
        
        return userProxy;
    } 
}

4. 测试类

package com.dynamicProxy;

public class Test {
    public static void main(String[] args) {
        User u = new UserImpl();
        
        User u2 = new UserImplProxy(u).getProxyObject();
        
        int result = u2.add(20,  4);
        System.out.println(result);
        
        result = u2.sub(20,  4);
        System.out.println(result);
    }
}

 

posted @ 2018-04-18 15:08  林**  阅读(123)  评论(0编辑  收藏  举报