JAVA动态代理学习

学习了一篇文章,觉得挺好,记录一下 

参考:https://www.cnblogs.com/gonjan-blog/p/6685611.html

 

 

 利用java实现动态代理

package com.example.demo;

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

public class MyinvocationHandler<T> implements InvocationHandler {
    T target;

    public MyinvocationHandler(T target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        System.out.println("代理执行" + method.getName() + "方法");
        //可以在代理中加入任意通用方法

        Object result = method.invoke(target, args);
        return result;
    }
}
package com.example.demo;

public interface Person {
    void go();
}

package com.example.demo;

public class Student implements Person {
    @Override
    public void go() {
        System.out.println("奔跑吧");
    }
}

调用执行:

   public static void main(String[] args) {
        Person st = new Student();
        InvocationHandler in = new MyinvocationHandler<Person>(st);
        Person stproxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class<?>[]{Person.class}, in);
        stproxy.go();
    }

执行结果:

 

posted @ 2019-12-03 18:19  张利锋  阅读(215)  评论(0编辑  收藏  举报