JDK的动态代理详解

文章目录


JDK动态代理的实现流程:

  • 首先创建一个接口,里面有一个基本的需求
  • 接着创建一个实现类,重写这个需求
  • 创建一个动态代理类,
    1.里面new一个InvocationHandler,重写里面的invoke方法;
    2.获取实现类的class对象中的具体方法;
    3.在invoke方法中调用实现类方法,之后添加增强的方法;
    4.根据Proxy方法中的newProxyInstance的方法获取接口的代理对象;
    5.代理对象代理接口之后,获取接口里面的方法来实现增强的效果

具体的代码实现:

//要代理的接口Persion 
package main.java.cn.xiaomi.proxy01;
public interface Persion {
    
    
    public void GiveMoney();
}
//接口的实现类Student 
package main.java.cn.xiaomi.proxy01;
import main.java.cn.xiaomi.proxy.Persion;

public class Student implements Persion {
    
    
    @Override
    public void GiveMoney() {
    
    
        System.out.println("student give money");
    }
}
//接口的代理类
package main.java.cn.xiaomi.proxy01;

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

public class ProxyStudent  {
    
    
    public static void main(String[] args) throws NoSuchMethodException {
    
    
    	//创建实现类的对象,目的是为了获取实现类里面的方法
        Student student = new Student();
        //通过反射机制,来获取类中的方法,GiveMoney为实现类中的方法名,null为方法的参数
        Method giveMoney = Student.class.getMethod("GiveMoney", null);
		//创建一个InvocationHandler(调用处理器),他是个接口,所以需要重写里面的invoke方法
		//通过giveMoney 来调用实现类student中的方法,之后添加需要增强的方法
        InvocationHandler handler = new InvocationHandler() {
    
    
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
                giveMoney.invoke(student,null);
                  System.out.println("student方法被增强了");
                return null;
            }
        };
		//创建接口的代理对象,其中三个参数是:接口的加载器,接口的字节码文件,处理器
        Persion persion = (Persion) Proxy.newProxyInstance(Persion.class.getClassLoader(), new Class[]{
    
    Persion.class}, handler);
        //调用代理对象中的方法来增强。
        persion.GiveMoney();
    }

}

Guess you like

Origin blog.csdn.net/m0_57184607/article/details/121026912