Java中动态代理工作流程

  当谈到动态代理就会想到接口,因为接口是一种规范,动态代理对象通过接口便会很清楚地知道他的实现类(被代理对象)是何种类型的(即有哪些方法)。Now,然我们来开始编写一个例子来了解动态代理的全过程

第一:既然接口那么好使,就先定义一个接口Action

package com.lzj.Spring_first.testAgentMyPractice;

public interface Action {
//    定义方法
    public void say();
    public void doSomething();
}

第二:既然有了接口,接下来咱们就得有实现类。所以再定义Action的实现类ActionImpl

package com.lzj.Spring_first.testAgentMyPractice;

public class ActionImpl implements Action {

    @Override
    public void say() {
        System.out.println("Study hard...day day up...");

    }

    @Override
    public void doSomething() {
        System.out.println("Nothing wants to be done...");

    }

}

第三:既然要代理,就必须弄个代理对象,我这里是实现的java.lang.reflect下的InvocationHandler接口。spring框架也有自己的InvocationHandler接口,这个只要保证你引入的包一致即可,不要引了java.lang下的又引spring下的就行

package com.lzj.Spring_first.testAgentMyPractice;

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

public class AgentFunc implements InvocationHandler{
//    要被代理的对象
    Object target;
    public AgentFunc(Object target) {
        this.target = target;
    }
//    代理对象执行的方法
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // TODO Auto-generated method stub
        return method.invoke(target, args);
    }

}

第四:完事具备,就差一个测试方法了,Come on...

package com.lzj.Spring_first.testAgentMyPractice;

import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
//        要被代理的对象
        ActionImpl actionImpl = new ActionImpl();
//       第一个是代理类在哪个类执行时加载
//       第二个参数是实现类实现的接口,而不能写成Action.class.getInterfaces()显然是错误的,因为该接口没有接口,而且第二参数要的是实现类的接口即Action
//       第三个则是代理类的执行方法所在,即我们写的代理类
        Action action = (Action) Proxy.newProxyInstance(Action.class.getClassLoader(), new Class[]{Action.class}, new AgentFunc(actionImpl));
     action.say();
  }
}

 最后输出结果...亲测成功,自己可以去试试!好了以上仅是自己对动态代理的独自见解,如有出处可以留言...

原文地址:https://www.cnblogs.com/lzj123/p/6496963.html