`

动态代理

    博客分类:
  • Java
阅读更多
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface ISubject{ 
	public void doSomething() ; 
}
class RealSubject implements ISubject{ //真是主题

	@Override
	public void doSomething() { //表示要实行一些处理操作,   事物
		System.out.println("吃饭");
	}
}
class ProxyImpl implements InvocationHandler{
	private Object real ;
	public Object bind(Object obj){
		this.real = obj ;  //  真实对象
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this) ; 
	}
	public void prepare(){
		System.out.println("准备饭菜");
	}
	public void clean(){
		System.out.println("收拾餐桌");
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		this.prepare();
		Object ret = method.invoke(this.real, args) ; //调用真是方法
		this.clean();
		return ret;
	} 
}
public class Hello {
	public static void main(String[] args) {
		ISubject subject = (ISubject) new ProxyImpl().bind(new RealSubject()) ; 
		subject.doSomething();
	}
}	

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics