JAVA动态代理学习

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

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

JAVA动态代理学习_第1张图片

 

 

 利用java实现动态代理

package com.example.demo;

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

public class MyinvocationHandler 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(st);
        Person stproxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class[]{Person.class}, in);
        stproxy.go();
    }

执行结果:

JAVA动态代理学习_第2张图片

 

你可能感兴趣的:(JAVA动态代理学习)