动态代理
动态代理
利用Java的反射技术(Java Reflection),在运行时创建一个实现某些给定接口的新类(也称“动态代理类”)及其实例(对象),代理的是接口(Interfaces),不是类(Class),也不是抽象类。在运行时才知道具体的实现,spring aop就是此原理。
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
newProxyInstance,方法有三个参数:
loader: 用哪个类加载器去加载代理对象
interfaces:动态代理类需要实现的接口
h:动态代理方法在执行时,会调用h里面的invoke方法去执行
定义一个接口:
public interface IVehical { void run(); }
要扩展的类:
public class Car implements IVehical { public void run() { System.out.println("Car会跑"); } }
调用处理类invocationhandler
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class VehicalInvacationHandler implements InvocationHandler { private final IVehical vehical; public VehicalInvacationHandler(IVehical vehical){ this.vehical = vehical; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("---------before-------"); Object invoke = method.invoke(vehical, args); System.out.println("---------after-------"); return invoke; } }
invoke三个参数:
proxy:就是代理对象,newProxyInstance方法的返回对象
method:调用的方法
args: 方法中的参数
import java.lang.reflect.Proxy;
public class App { public static void main(String[] args) { IVehical car = new Car(); IVehical vehical = (IVehical)Proxy.newProxyInstance(car.getClass().getClassLoader(), Car.class.getInterfaces(), new VehicalInvacationHandler(car)); vehical.run(); } }
上面代码中,代理car对象,调用run方法时,自动执行invocationhandler中的invoke方法。

可以打印一下:
System.out.println(vehical.getClass());


浙公网安备 33010602011771号