java代理笔记:静态代理、JDK动态代理、CGlib动态代理

1.静态代理

//接口类
public interface Hello{
     void say(String name);   
 }    
//实现类
 public class HelloImpl implements Hello{
        @Override
        public void say(String name){
            System.out.println(name);
        }
  }
//代理类
 public class HelloProxy implements Hello{
    private Hello hello;
    
    public HelloProxy(){
        hello=new HelloImpl();
    }
    
    @Override
    public void say(String name){
            before();
            hello.say(name);
            after();
    }
    
    private void before(){
        
    }
    
    private void after(){
        
    }
}
  public static void main(String[] args){
            Hello helloProxy=new HelloProsy()
            helloProxy.say("Hi");
   } 

JDK动态代理

  //动态代理类
  /* param1: ClassLoader
   * param2: 该实现类的所有接口
   * param3: 动态代理类对象
   */
public class DynamicProxy implements InvocationHandler{
    private Object target;
    public DynamicProxy(Object target){
        this.target=target
    }
    
    @Override
    public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{    
        before();
        Object result=method.invoke(target,args);
        after();
        return result
    }
    ...
}
   
public static void main(String[] args){
    Hello hello =new HelloImpl();
    DynamicProxy dynamicProxy=new DynamicProxy(hello);
    Hello helloProxy=(DynamicProxy)Proxy.newProxyInstance(
    hello.getClass().getClassLoader(),hello.getClass().getInterfaces(),dynamicProxy
    );
    helloProxy.say("Hi");
}

CGlib动态代理

  public class CGLibProxy implements MethodInterceptor{
    public  T getProxy(Class cls){
        return (T) Enhancer.create(cls,this);
    }
    
    public Object intercept(Object obj,Method method,Object[] args,MethodProxy proxy) throws Throwable{
        before();
        Object result=proxy.invokeSuper(obj,args);
        after();
        return result;
    }
    ...
}

public static void main(String[] args){
    CGLibProxy cGLibProxy =new CGLibProxy();
    Hello helloProxy=cGLibProxy.getProxy(HelloImpl.class);
    helloProxy.say("Hi");
}

你可能感兴趣的:(java代理笔记:静态代理、JDK动态代理、CGlib动态代理)