设计模式-代理模式-动态代理

Service接口

package spring.aop.DynamicProxy;

/**
 * Created with IDEA
 * author:liuhaotian
 * Date:2019/9/1 23:03
 * Description:
 */
public interface Service {
    String sellCar(String carName);
}

Service实现类

package spring.aop.DynamicProxy;

/**
 * Created with IDEA
 * author:liuhaotian
 * Date:2019/9/1 23:04
 * Description:
 */
public class ServiceImpl implements Service{
    @Override
    public String sellCar(String carName) {
        return carName + " is ready";
    }
}

InvocationHandler 实现类

package spring.aop.DynamicProxy;

import basic.MyInterface;

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

/**
 * Created with IDEA
 * author:liuhaotian
 * Date:2019/9/1 23:05
 * Description:
 */
public class MyInvocationHandler implements InvocationHandler {
    private Object target;

    //在构造函数中初始化target对象
    public MyInvocationHandler(Object target) {
        this.target = target;
    }


    /**
     * 通过invoke方法调用target对象中的方法
     *
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxyService, Method method, Object[] args) throws Throwable {
         System.out.println("要执行的方法:" + method.getName());
        //通过 method 的 invoke 方法调用 target 类中的方法
        //!!!!! method(对象,入参)要用目标真实对象
        Object result = method.invoke(target, args);
         System.out.println("method.getName() 执行结果:" + result.toString());
        return result;
    }
}

测试类

package spring.aop.DynamicProxy;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * Created with IDEA
 * author:liuhaotian
 * Date:2019/9/1 23:11
 * Description:
 */
public class DynamicProxyTest {

    @Test
    public void test(){
        //要被代理的真实对象
        Service service = new ServiceImpl();
        //将真实对象交给代理
        InvocationHandler invocationHandler = new MyInvocationHandler(service);
        //创建代理对象
        Service proxyService = (Service)Proxy.newProxyInstance(service.getClass().getClassLoader(),
                service.getClass().getInterfaces(),invocationHandler);
        System.out.println(proxyService.sellCar("BMM"));
    }

}

输出结果:
要执行的方法:sellCar
method.getName() 执行结果:BMM is ready
BMM is ready

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值