动态代理模式之=====接口代理

1.Proxy.newInstance(ClassLoader[] ,  new Class[] interfaces,InvocationHandler h)

2.InvocationHandler 实现类 invoke( Object proxy,Method method,Object[] ...args)

用途:1.实现接口方法; 

interface B{
   User getUser(int id);
    
    void  getUsersCount();
}

public class A implements InvocationHandler{
    
    public  Object   bind(){
           
       return Proxy.newInstance(
B.class.getClassLoader(),new Class[]{B.class},this);


    
    public Object invoke(Object proxy,Method method,Object[] ..args){
         if(method.getName().eques("getUser")){
               :获取参数,返回值
               ;重写方法
         
    
               return  方法返回值;
        }       

  

2.对实现接口的类的方法进行拦截,扩展新的方法内容;方法拦截。

public class A implements InvocationHandler{
    private Object target;
    public  Object   bind(Object delegate){
           thhis.target=delegate;
    
       return Proxy.newInstance(target.getClass().getClassLoader(),target.getClass().getInterfaes(),this);


    
    public Object invoke(Object proxy,Method method,Object[] ..args){
                sout("方法执行前");
                Object    result= method.invoke(target,...args);
                sout(“方法执行后”)
           return result;
        }           

  

原文地址:https://www.cnblogs.com/chencn/p/12325830.html