public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
InvocationHandler h) throws IllegalArgumentException
// get a new Proxy Instance
// loader 通过反射机制获取到的受代理对象的类加载器
// interfaces 受代理对象实现的业务接口组(这个动态代理所能代理的方法便是这些业务接口里面实现的方法)
// h Proxy 实例被调用时便会将调用的 Method 对象与参数传给 h 中实现的 invoke 方法
InvocationHandler is the interface implemented by the invocation handler of a proxy instance.
Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler -- Java SE8 API
每一个 Proxy 实例都需要一个 InvocationHandler 接口的实现与其配合工作,当一个 Proxy 的方法被调用,这个方法调用会被编码并将信息发送给 Invocation Handler 里定义的 invoke 方法。下面来看看 invoke 方法。
Object invoke(Object proxy, Method method, Object[] args) throws Throwable
// proxy 被调用的 Proxy 实例
// method 调用的方法对象(这个方法应该是 Proxy 实例所实现了的接口里面定义的方法,即上一步参数 interfaces 中定义的方法)
// args 调用时传入的参数
// ProxyFactory.java
package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 静态工厂类,需要实现 InvocationHandler 接口,这样才能够调用 newProxyInstance()
public class ProxyFactory implements InvocationHandler{
private Object target;
public ProxyFactory(Object target) {
this.target = target;
}
public Object getProxyInstance() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), // 运用反射机制获取接口组
this); // 该方法三个参数里的 h 恰好就是实现了 InvocationHandler 接口的 this
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.printf("start Proxy the method is %s\n", method);
Object aobj = method.invoke(target, args);
return aobj;
}
}
// Subject.java
package Proxy;
// 主题接口的定义
public interface Subject {
public void doSomething();
}
// RealSubject.java
package Proxy;
// 一个真实主题类
public class RealSubject implements Subject{
public RealSubject() {
}
@Override
public void doSomething() {
System.out.println("the RealSubject is invoked");
}
}
// ClientTest.java
package Proxy;
// 客户测试类
public class ClientTest {
public static void main(String[] args) {
RealSubject target = new RealSubject();
ProxyFactory afactory = new ProxyFactory(target); // 生成工厂实例
Subject aproxy = (Subject) afactory.getProxyInstance(); // 生成代理实例
aproxy.doSomething(); // 通过代理实现业务功能
}
}
Cglib 代理是子类代理,即它是在内存中构建一个受代理类的子类,从而实现代理以及功能扩展。
这个实现需要 Cglib jar 包(Spring 核心包内已有),并调用里面设定好的方法即可。这个留到学习 Spring 的时候再填坑。
原文:https://www.cnblogs.com/Melles/p/10740079.html