java代理
java代理共分3类:
静态代理,动态代理,子类代理
1.静态代理:
接口类 MyRequest:
public interface MyRequest {
public void request();
}
目标类:
public class GoalRequest implements MyRequest{
public void request(){
System.out.println("目标请求");
}
}
静态代理类:
public class RequestProxy implements MyRequest{
private MyRequest myrequest;
public RequestProxy(MyRequest myrequest){
this.myrequest = myrequest;
}
public void request(){
System.out.println("代理执行");
myrequest.request();
}
}
测试类:
public static void main( String[] args )
{
GoalRequest goalRequest = new GoalRequest();
RequestProxy reqproxy = new RequestProxy(goalRequest);
reqproxy.request();
}
2.动态代理:
动态代理不必实现接口类,主要是通过Proxy.newProxyInstance方法来实现,具体看代码
代理工厂类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactory {
private Object target;
public ProxyFactory(Object target){
this.target = target;
}
public Object getProxyInstance(){
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
Object returnValue = method.invoke(target, args);
System.out.println("动态代理执行");
return returnValue;
}
}
);
}
}
测试类:
public static void main(String[] args) {
MyRequest goalRequest = new GoalRequest();
MyRequest proxy = (MyRequest) new ProxyFactory(goalRequest).getProxyInstance();
proxy.request();
}
3.Cglib子类代理,Aop中常用,用于目标类没有实现任何接口的情况
目标类:
public class BaseProxy {
public void request(){
System.out.println("未实现任何接口的目标对象");
}
}
子类代理类:
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
public class CglibProxyFactory implements MethodInterceptor{
private Object target;
public CglibProxyFactory(Object target){
this.target = target;
}
//创建代理类
public Object getProxyInstance(){
Enhancer eh = new Enhancer();
eh.setSuperclass(target.getClass());
eh.setCallback(this);
return eh.create();
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable{
Object returnValue = method.invoke(target, args);
System.out.println("子类代理执行");
return returnValue;
}
}
测试类:
public static void main(String[] args) {
BaseProxy target =new BaseProxy();
BaseProxy proxy =(BaseProxy)new CglibProxyFactory(target).getProxyInstance();
proxy.request();
}
学习了岑宇大大的博客后自己写了下代码,写的没有岑宇大大好,更详细的内容可以去岑宇大大的博客看。
传送门:https://www.cnblogs.com/cenyu/p/6289209.html