public class ProxyFactory {
/**
* Jdk动态代理(代理对象必须实现接口)
* @param obj 委托对象
* @return 代理对象
*/
public Object getJdkProxy(Object obj) {
// 获取代理对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
result = method.invoke(obj,args);
return result;
}
});
}
/**
* 使用cglib动态代理
* @param obj 委托对象
* @return
*/
public Object getCglibProxy(Object obj) {
return Enhancer.create(obj.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Object result = null;
result = method.invoke(obj,objects);
return result;
}
});
}
}
动态代理通用工具类(jdk、cglib)
最新推荐文章于 2022-12-05 16:23:05 发布