java动态代理_原理分析

最基础的动态代理Demo

主函数

public class App {
    public static void main(String[] args) {
        System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");

        Integer a = 0;
        IVehical car = new Car();
        InvocationHandler handler = new VehicalInvacationHandler(car);
        IVehical vehical = (IVehical) Proxy.newProxyInstance(IVehical.class.getClassLoader(), new Class[]{IVehical.class}, handler);
        //System.out.println(vehical);
        vehical.run();
        vehical.boom();
    /*
    newProxyInstance,方法有三个参数:
loader: 用哪个类加载器去加载代理对象
interfaces:动态代理类需要实现的接口
h:动态代理方法在执行时,会调用h里面的invoke方法去执行
     */
}

业务逻辑接口IVehical

package PlayProxy;

public interface IVehical {
    void run();
    void boom();
}

业务逻辑类Car

package PlayProxy;

public class Car implements IVehical{


    public void run() {
        System.out.println("Car会跑");
    }

    public void boom() {
        System.out.println("Boom!");
    }
}

InvocationHandler实现类

package PlayProxy;

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

public class VehicalInvacationHandler implements InvocationHandler {
    private final Object target;
    public VehicalInvacationHandler(Object o){
        this.target = o;
    }
/*
invoke三个参数:
proxy:就是代理对象,newProxyInstanc
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值