Java Dynamic proxy

//Count.java
public interface Count {
    public int add(int a, int b);
}

// CountImpl.java
public class CountImpl implements Count{

    @Override
    public int add(int a, int b) {
        // TODO Auto-generated method stub
        return a+b;
    }
}
//Run.java
public interface Run {
    public float inc(float distance);
}

//RunImpl.java
public class RunImpl implements Run{
    float dis;

    @Override
    public float inc(float distance) {
        // TODO Auto-generated method stub
        return dis+distance;
    }
}
//MyProxy.java

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyProxy implements java.lang.reflect.InvocationHandler{
    
    Object proxyee;
    
    public Object bind(Object to_be_proxyed){
        proxyee=to_be_proxyed;
        Object proxy=Proxy.newProxyInstance(proxyee.getClass().getClassLoader(),proxyee.getClass().getInterfaces(), this);
        return proxy;
    } 

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //do something before calling proxyee's method
        Object result=method.invoke(proxyee, args);
        //do something after calling proxyee's method
        return result;
    }
    
    public static void main(String[] args){
        
        CountImpl ci=new CountImpl();
        RunImpl ri=new RunImpl();
        
        MyProxy myproxy=new MyProxy();
        
        Run r=(Run)myproxy.bind(ri);
        System.out.println(r.inc(3));
        /**why it is still 3 ?**/
        System.out.println(r.inc(3));
        
        Count c=(Count)myproxy.bind(ci);
        System.out.println(c.add(1, 2));
        System.out.println(c.add(1, 3));
    }

}
原文地址:https://www.cnblogs.com/chaseblack/p/4722591.html