java代理

 

 

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

public class DynamicProxy implements InvocationHandler{	
	
	private Object object;	

    public Object bind(Object object){           
        this.object = object;          
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(),this);           
    }

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {		
		//do sth1		
		//call 
		Object result = method.invoke(object, args);
        //do sth2		
        //return result;        
        return "something else";
	}
}
    	//IntfImpl实现接口Intf1和Intf2
	Object proxy = new DynamicProxy().bind(IntfImpl);    	
    	Intf1 intf1 = (Intf1)proxy;   
    	Intf2 intf2 = (Intf2)proxy;  
    	intf1.do1();
    	intf2.do2();

你可能感兴趣的:(java)