JDK动态代理简单实现

创建交通工具接口:Vehicle

package proxy;

public interface Vehicle {
    void drive();
} 

创建充电接口:Rechargable

package proxy;

public interface Rechargable {
    void recharge();
}

创建电动车实现类:ElectricCar

package proxy;

public class ElectricCar implements Rechargable, Vehicle {
  
    @Override  
    public void drive() {  
        System.out.println("电动车跑起来了!!!");
    }  
  
    @Override  
    public void recharge() {  
        System.out.println("电动车正在充电!!!");
    }  
  
}  

创建测试类:Test

package proxy;

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

/**
 * @ClassName Test
 * @Description TODO
 * @Date 2019/8/6 9:16
 * @Created by sunyiwei
 */
public class Test {
    public static void main(String[] args){
        ElectricCar car = new ElectricCar();
        // 1.获取对应的ClassLoader
        ClassLoader classLoader = car.getClass().getClassLoader();
        // 2.获取ElectricCar 所实现的所有接口
        Class[] interfaces = car.getClass().getInterfaces();
        /*
          3.根据上面提供的信息,创建代理对象 在这个过程中,
                 a.JDK会通过根据传入的参数信息动态地在内存中创建和.class 文件等同的字节码
                 b.然后根据相应的字节码转换成对应的class,
                 c.然后调用newInstance()创建实例
         */

        Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("将要调用 " + method.getName() + " 方法!!!");
                method.invoke(car);
                System.out.println(method.getName() + " 调用完成!!!");
                return null;
            }
        });
        Vehicle vehicle = (Vehicle) proxy;
        vehicle.drive();
        Rechargable rechargable = (Rechargable) proxy;
        rechargable.recharge();
    }
}

你可能感兴趣的:(JDK动态代理简单实现)