proxy动态代理

proxy动态代理

 * 真实对象:定义目标操作  
 * @author WalkingDog  
 *  
 */  
public class RealSubject implements Subject {  
    @Override  
    public void doSomething() {  
        System.out.println("RealSubject.doSomething");  
    }  
}  
 
 
 
 
import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
  
public class DynamicProxy implements InvocationHandler {  
    private Object object;  
    public DynamicProxy(Object object) {  
        this.object = object;  
    }  
  
    @Override  
    public Object invoke(Object proxy, Method method, Object[] args)  
            throws Throwable {  
        System.out.println("Before Invoke ! method : " + method);  
          
        //我们可以再代理方法调用前后添加功能   
        Object result = method.invoke(object, args);  
          
        System.out.println("object : " + object + "\tresult : " + result + "\targs : " + args);  
        System.out.println("After Invoke !");  
        return result;  
    }  
}  
 
 
import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Proxy;  
  
/** 
 * 客户端 
 * @author WalkingDog 
 * 
 */  
public class Client {  
    public static void main(String[] args) throws Exception {  
          
        //创建目标对象,也就是被代理对象   
        RealSubject realSubject = new RealSubject();  
          
        //将目标对象交给代理   
        InvocationHandler handler = new DynamicProxy(realSubject);  
          
//      Class<?> proxyClass = Proxy.getProxyClass(Subject.class.getClassLoader()   
//              , new Class[]{Subject.class});   
//      Subject subject = (Subject)proxyClass.getConstructor(new Class[]{InvocationHandler.class})   
//              .newInstance(new Object[]{handler});   
          
        //返回代理对象,相当于上面两句   
        Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),  
                realSubject.getClass().getInterfaces(),  
                handler();  
          
        //叫代理对象去doSomething(),其实在代理对象中的doSomething()中还是会   
        //用handler来调用invoke(proxy, method, args) 参数proxy为调用者subject(this),   
        //method为doSomething(),参数为方法要传入的参数,这里没有   
        subject.doSomething();  
    }  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值