創(chuàng)建交通工具接口:Vehicle
package proxy;
public interface Vehicle {
void drive();
}
創(chuàng)建充電接口:Rechargable
package proxy;
public interface Rechargable {
void recharge();
}
創(chuàng)建電動車實現(xiàn)類:ElectricCar
package proxy;
public class ElectricCar implements Rechargable, Vehicle {
@Override
public void drive() {
System.out.println("電動車跑起來了!!!");
}
@Override
public void recharge() {
System.out.println("電動車正在充電!!!");
}
}
創(chuàng)建測試類: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.獲取對應(yīng)的ClassLoader
ClassLoader classLoader = car.getClass().getClassLoader();
// 2.獲取ElectricCar 所實現(xiàn)的所有接口
Class[] interfaces = car.getClass().getInterfaces();
/*
3.根據(jù)上面提供的信息,創(chuàng)建代理對象 在這個過程中,
a.JDK會通過根據(jù)傳入的參數(shù)信息動態(tài)地在內(nèi)存中創(chuàng)建和.class 文件等同的字節(jié)碼
b.然后根據(jù)相應(yīng)的字節(jié)碼轉(zhuǎn)換成對應(yīng)的class,
c.然后調(diào)用newInstance()創(chuàng)建實例
*/
Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("將要調(diào)用 " + method.getName() + " 方法!!!");
method.invoke(car);
System.out.println(method.getName() + " 調(diào)用完成!!!");
return null;
}
});
Vehicle vehicle = (Vehicle) proxy;
vehicle.drive();
Rechargable rechargable = (Rechargable) proxy;
rechargable.recharge();
}
}