动态代理

1、动态代理的接口

package cn.proxy;

public interface ProxyInterface {

public void doSomething();

}


2、实现类

package cn.proxy;

public class ProxyImpl implements ProxyInterface {

@Override

public void doSomething() {

// TODO Auto-generated method stub

System.out.println("实现类");

}

}


3、要实现代理的类

package cn.proxy;

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

public class ProxyHandler implements InvocationHandler{

private Object object;  //传入一个Object类型的对象,给该类中的invoke方法调用

public ProxyHandler() {

// TODO Auto-generated constructor stub

}

public ProxyHandler(Object object) {

this.object = object;

}

/**

*    proxy:被代理的实现类

*    method:被代理的接口

*    args:参数,代理后的类

*/

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

System.out.println("执行动态代理前!");

Object result = method.invoke(object, args);

System.out.println("执行动态代理后!");

return result;

}


//获取代理后的对象

public Object getProxy() {

return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), object.getClass().getInterfaces(), this);

}

}


4、测试类

package cn.proxy;

import java.lang.reflect.Proxy;

public class ProxyTest {

public static void main(String[] args) {

ProxyInterface proxyInterface = new ProxyImpl();

proxyInterface.doSomething();

ProxyHandler proxyHandler = new ProxyHandler(proxyInterface);

ProxyInterface proxy = (ProxyInterface) Proxy.newProxyInstance(proxyInterface.getClass().getClassLoader(), proxyInterface.getClass().getInterfaces(), proxyHandler);

proxy.doSomething();

}

}


5、测试结果

实现类

执行动态代理前!

实现类

执行动态代理后!


6、背后的原理

JDK动态代理实现原理

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容