代码改变世界

动态代理完全理解实践

2019-02-23 13:58  Spiderman25  阅读(65)  评论(0)    收藏  举报

public interface A {
    public void pay();
}
 
public interface B {
    public void eat();
}

 

public class AImpl implements A{
    @Override
    public void pay() {
        System.out.println("玩");
    }
}

 

public class BImpl implements B {
    @Override
    public void eat() {
        System.out.println("吃");
    }
}

 

public class MyInvocationHandler implements InvocationHandler {
    private Object obj;
    private Object obj1;
    public Object bind(Object obj,Object obj1){
        this.obj=obj;
        this.obj1=obj1;
        Class<?>[] ainterfaces = obj.getClass().getInterfaces();
        Class<?>[] binterfaces = obj1.getClass().getInterfaces();
        int al=ainterfaces.length;
        int bl=binterfaces.length;
        ainterfaces=Arrays.copyOf(ainterfaces,al+bl);
        System.arraycopy(binterfaces,0,ainterfaces,al,bl);
        return Proxy.newProxyInstance(MyInvocationHandler.class.getClassLoader(), ainterfaces,this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method[] methods = obj.getClass().getMethods();
        Method[] methods1 = obj1.getClass().getMethods();
        for(Method m:methods){
            if(m.getName().equals(method.getName())){
                Object temp=method.invoke(this.obj,args);
                return temp;
            }
        }
        for(Method m:methods1){
            if(m.getName().equals(method.getName())){
                Object temp=method.invoke(this.obj1,args);
                return temp;
            }
        }
        return null;
    }
}
 
public class DynaProxyDemo {
    public static void main(String[] args){
        MyInvocationHandler handler=new MyInvocationHandler();
        Object a= handler.bind(new AImpl(),new BImpl());
        A a1= (A) a;
        B b1= (B) a;
        a1.pay();
        b1.eat();
        //a.eat();
        /*B b= (B) handler.bind(new BImpl());
        b.eat();*/
    }
}