jdk动态代理
实现步骤
- 新建一个接口
- 新建一个接口的实现类
- 新建一个代理类,实现InvocationHandler接口,实现invoke方法-> method.invoke(…)
- 在代理类中创建代理方法newProxy,传入目标对象,通过目标对象获取类加载器、类接口,调用Proxy.newProxyInstance方法获取代理对象
- 通过代理对象调用具体方法
代码示例
新建一个接口
package com.demo.rpc.proxy;public interface NewsService {String queryById(long newsId);
}
新建一个接口的实现类
package com.demo.rpc.proxy;public class NewsServiceImpl implements NewsService {@Overridepublic void queryById(long newsId) {System.out.println("成龙亿元豪宅司法拍卖被撤回 原定于明日开拍 " + newsId);}
}
新建一个代理类
package com.demo.rpc.proxy;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public class JDKProxy implements InvocationHandler {Object targetObject;public Object newProxy(Object targetObject) {this.targetObject = targetObject;return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("代理之前");Object invoke = method.invoke(targetObject, args);System.out.println("代理之后");return invoke;}
}
调用测试
@Testpublic void jdkProxy(){NewsServiceImpl newsServiceImpl = new NewsServiceImpl();JDKProxy proxy = new JDKProxy();NewsService newsService = (NewsService)proxy.newProxy(newsServiceImpl);newsService.queryById(1);}
cglib动态代理实现
实现步骤
- 创建一个实现类
- 新建一个代理类,实现MethodInterceptor接口,实现intercept方法-> method.invoke(…)
- 在代理类创建代理方法newProxy并传入目标对象,通过Enhancer创建代理类
- 通过代理对象调用具体方法
创建一个实现类
package com.demo.rpc.proxy;public class HelloService {public void sayHello(){System.out.println("hello");}
}
新建一个代理类
package com.demo.rpc.proxy;import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;import java.lang.reflect.Method;public class CGLIBProxy implements MethodInterceptor {Object targetObject;public Object newProxy(Object targetObject){this.targetObject = targetObject;Enhancer enhancer = new Enhancer();enhancer.setSuperclass(targetObject.getClass());enhancer.setCallback(this);Object proxyObj = enhancer.create();return proxyObj;}@Overridepublic Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {System.out.println("代理之前");Object invoke = method.invoke(targetObject, args);System.out.println("代理之后");return invoke;}
}
调用测试
@Testpublic void CGLIBProxy(){CGLIBProxy proxy = new CGLIBProxy();HelloService helloService = (HelloService)proxy.newProxy(new HelloService());helloService.sayHello();}