JAVA动态代理Porxy

咱就直接实例开头了哈:

我们需要一个工具类:People(接口里面不一定非要是抽象方法哦!!!!大家可以自己扩展一下)

public interface People {
      public String Information();
}

再来一个重写Information的实现类Teather

public class Teather implements People {

    public String Information() {
        // TODO Auto-generated method stub
        System.out.println("The Teacher is teaching English");
        return "Mr Liuzhi";
    }

}

 

接下来就是主要的代码了,看看我是怎样实现的动态代理:

/*
 * @author Mr liu
 * 动态代理的基本步骤和操作
 * 1、实现InvocationHandler,重写invoke方法
 * 2、通过invoke的代理实例上处理方法调用并返回结果。(Runnable和invoke的区别就在于有无返回值)
 * 3、找到要找代理的对象,然后实例化为代理对象,进行下一步操作
 * 4、通过Proxy.newProxyInstance(类加载器,接口,InvocationHandler对象)实现动态代理
 */
public class Porxy implements InvocationHandler {
    /**
     * @param args
     */
    Object obj;
    public Porxy(Object obj){
        this.obj=obj;
    }
    public Porxy(){
        
    }

    public static void main(String[] args) {
            //需要代理对象
            People person=new Teather();
            //添加需要代理对象
            InvocationHandler people=new Porxy(person);
            //实现和加载代理对象
            People people2=(People)Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(),people);
            String mess=people2.Information();
            System.out.println(mess);
    }
    public Object invoke(Object arg0, Method arg1, Object[] arg2)
            throws Throwable {
        System.out.println("Porxy before");
        Object result = arg1.invoke(this.obj, arg2);    
        return result;
    }

}

输出结果:

结尾:希望各位大佬多多评论,你们的评论就是我学习的动力!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值