首页 > 其他 > 详细

动态代理模式之=====接口代理

时间:2020-02-18 14:05:12      阅读:36      评论:0      收藏:0      [点我收藏+]

1.Proxy.newInstance(ClassLoader[] ,  new Class[] interfaces,InvocationHandler h)

2.InvocationHandler 实现类 invoke( Object proxy,Method method,Object[] ...args)

用途:1.实现接口方法; 

interface B{
   User getUser(int id);
    
    void  getUsersCount();
}

public class A implements InvocationHandler{
    
    public  Object   bind(){
           
       return Proxy.newInstance(
B.class.getClassLoader(),new Class[]{B.class},this);


    
    public Object invoke(Object proxy,Method method,Object[] ..args){
         if(method.getName().eques("getUser")){
               :获取参数,返回值
               ;重写方法
         
    
               return  方法返回值;
        }       

  

 

2.对实现接口的类的方法进行拦截,扩展新的方法内容;方法拦截。

public class A implements InvocationHandler{
    private Object target;
    public  Object   bind(Object delegate){
           thhis.target=delegate;
    
       return Proxy.newInstance(target.getClass().getClassLoader(),target.getClass().getInterfaes(),this);


    
    public Object invoke(Object proxy,Method method,Object[] ..args){
                sout("方法执行前");
                Object    result= method.invoke(target,...args);
                sout(“方法执行后”)
           return result;
        }           

  

 

动态代理模式之=====接口代理

原文:https://www.cnblogs.com/chencn/p/12325830.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!