本文参考:java动态代理Proxy.newProxyInstance-CSDN博客
一、动态代理定义
利用Java的反射技术,在运行期间创建可以实现某些给定接口的新类,称为动态代理类。
此处代理的接口(Interfaces),不是类(Class)。
动态代理是因为在运行时才知道具体的类的实现(接口对应不同的实现,动态调用)。
二、动态代理JDK的实现方法
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
newProxyInstance方法有三个参数:
(1)loader:用哪个类加载器去加载代理对象
(2)interfaces:动态代理类需要实现的接口
(3)InvocationHandler:动态代理方法在执行时,会调用此处的invoke方法去执行
invoke的原型:
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
}
}
1)proxy:就是代理对象,newProxyInstance方法的返回对象
2)method:调用的方法,此处为被代理对象的方法
3)args:方法中的参数,此处为被代理对象的方法的参数
invoke会根据被代理对象的方法个数被执行多次。
三、示例
(1)定义接口
public interface IVehical {
void run();
void show();
}
(2)实现接口
public class Car implements IVehical {
@Override
public void run() {
System.out.println("Car会跑");
}
@Override
public void show() {
System.out.println("Car show...");
}
}
(3)动态代理
public class ProxyTest {
public static void main(String[] args) {
IVehical car = new Car();
Object beanProxy = Proxy.newProxyInstance(
car.getClass().getClassLoader(),
car.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("run")){
System.out.println("---------before---------");
Object result = method.invoke(car, args);
System.out.println("---------after---------");
return result;
}else{
Object result = method.invoke(car, args);
return result;
}
}
}
);
((IVehical)beanProxy).run();
((IVehical)beanProxy).show();
}
}
(4)执行结果
---------before---------
Car会跑
---------after---------
Car show...