java JDK动态代理

/**
* jdk 动态代理:基于接口,动态代理类须要再运行时指定所代理对象实现的接口,客户端在调用动态代理对象的方法
* 时,调用请求会将请求自动转发给 InvocationHandler对象的invoke()方法,由invoke()方法来实现
* 对请求的统一处理
* 1.建立一个接口subject
* 2.建立一个须要被代理的对象,对象实现subject
* 3.建立 invoactionHandler 对象,该对象有一个Object属性,用于接收须要被代理的真实对象,
* 该接口做为代理实列的调用处理类
* 4.建立须要被代理的对象,将该对象传入 invocationHandler中
* 5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
* 返回一个Class类型的代理类,在参数中须要提供类加载器并须要指定代理的接口数组(与真实代理对象实现的接口列表一致)
*/
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class JDKProxy {
    public static void main(String[] args) {
        JDKEntryInterface entry = new JDKEntry("LiXiaolong");
        InvocationHandler handler = new JDKInvocationHandler();
        ((JDKInvocationHandler) handler).setObject(entry);
        JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance(
                JDKEntryInterface.class.getClassLoader(),
                new Class[]{ JDKEntryInterface.class },
                handler
        );
        proxy.exercise();
    }
}

 

1.建立一个接口
public interface JDKEntryInterface {
    void exercise();
}
2.建立一个须要被代理的对象,对象实现 JDKEntryInterface
public class JDKEntry implements JDKEntryInterface {
    private String name;

    public JDKEntry(String name){
        this.name = name;
    }

    @Override
    public void exercise() {
        System.out.println("my name is " + name + ". I want to exercise");
    }
}

3.建立 invoactionHandler 对象,该对象有一个Object属性,用于接收须要被代理的真实对象,
该接口做为代理实列的调用处理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JDKInvocationHandler implements InvocationHandler {
    private Object object;

    public void setObject(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("---------执行前动做-----------");
        Object result = method.invoke(this.object, args);
        System.out.println("---------执行后动做-----------");
        return result;
    }
}
4.建立须要被代理的对象,将该对象传入 invocationHandler中
JDKEntryInterface entry = new JDKEntry("LiXiaolong");
        InvocationHandler handler = new JDKInvocationHandler();
        ((JDKInvocationHandler) handler).setObject(entry);
5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

返回一个Class类型的代理类,在参数中须要提供类加载器并须要指定代理的接口数组(与真实代理对象实现的接口列表一致)
JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance(
                JDKEntryInterface.class.getClassLoader(),
                new Class[]{ JDKEntryInterface.class },
                handler
        );

   6.执行方法java

proxy.exercise();

 

执行结果:数组

---------执行前动做-----------
my name is LiXiaolong. I want to exercise
---------执行后动做-----------
相关文章
相关标签/搜索