首先看JDK的动态代理是怎么使用的
假设有一个需要代理的类叫Girl,这个Girl实现了MakeTrouble接口。
代码如下
public interface MakeTrouble {
void makeTrouble();
}
public class Girl implements MakeTrouble{
public void makeTrouble(){
System.out.println("girl makes trouble");
}
}
创建一个代理类,当然是为了重写某些方法的行为。首先需要定义这个新的行为,通过实现InvocationHandler接口。
public class GirlProxy implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
System.out.println("girl proxy makes trouble");
return null;
}
}
然而上面的这个类其实是个假代理。
因为这个类根本就是另起炉灶,除了名子跟Girl有关系之外,并没有真正的联系。
实际上,代理肯定对原有的方法的行为作修改或增加的。必须有原来的类参与进来。
那我们让Girl类参与进来之后,就变成了下面这个样子。
public class GirlProxy implements InvocationHandler {
private Girl girl;
public GirlProxy(Girl girl){
this.girl = girl;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
girl.makeTrouble();
System.out.println("girl proxy makes more trouble");
return null;
}
}
但是这里有一个问题,如果Girl类有多个需要代理的方法,InvocationHandler却只有1个invoke方法,如果新的代理类的所有方法都调这个invoke,不就所有的方法的行为都一样了吗。
事实上invoke可以代理多个方法的行为。那具体代理哪个方法是通过invoke方法的第2个和第3个参数来指示的。
那正确的写法就是下面这样
public class GirlProxy implements InvocationHandler {
private Girl girl;
public GirlProxy(Girl girl){
this.girl = girl;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
// 执行目标对象的方法
Object result = method.invoke(girl, args);
System.out.println("proxy method executed");
return null;
}
}
现在定义了新的代理类的行为。按理来说就可以给Girl创建代理类了。
创建代理类的实例的API长下面这个样子。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
可以理解,代理类是个新的类,所以需要指定ClassLoader,第2个参数则是定义新的代理类有哪些方法的, 第3个参数就是代理类的行为。
MakeTrouble a = (MakeTrouble)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
Girl.class.getInterfaces(),
girlProxy);
会有一个匿名的实现了MakeTrouble的代理类被生成,调用a.makeTrouble()的输出如下。
girl makes trouble
proxy method executed
动态代理的内部实现
来看看Proxy.newProxyInstance的代码
/**
* Returns an instance of a proxy class for the specified interfaces
* that dispatches method invocations to the specified invocation
* handler.
*/
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
* 创建这个代理类
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
* 调用代理类的构造方法来实例化代理类
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// constructorParams是一个常量
// private static final Class<?>[] constructorParams = { InvocationHandler.class };
// 代理类的构造方法是有一个参数的
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
// 这里把InvocationHandler实例传给代理类。
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
方法注释的意思就是 ,返回一个实现了指定接口的代理类的对象。这个代理类的每个方法都会被分发到InvocationHandler。
这样看就蛮简单了。代理类中会有所有interfaces的方法,然后这些方法的实现其实本质都是一样的。就是调InvocationHandler而已。
那接下来看创建代理类的代码,也就是Proxy#getProxyClass0()
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
// 检查接口数不要太多
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
// 可以看到这个代理类是有缓存机制的
return proxyClassCache.get(loader, interfaces);
}
proxyClassCache的定义如下
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
可以看到,代理类是通过ProxyClassFactory来创建的。
那我们看ProxyClassFactory的代码。
/**
* A factory function that generates, defines and returns the proxy class given
* the ClassLoader and array of interfaces.
*/
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
// 代理类的类名前缀
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
// 看来代理类的类名单纯就是自增的数字,第一个是$Proxy0,第二个是$Proxy1
private static final AtomicLong nextUniqueNumber = new AtomicLong();
/**
* 通过interfaces来创建代理类
*/
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
// 这一循环是一大堆检查
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
* 这一块不太重要,先不看
*/
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
* 代理类名
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
* 生成代理类的字节码,写入磁盘
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 通过字节码加载类
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}
看ProxyGenerator.generateProxyClass()
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
final byte[] var4 = var3.generateClassFile();
if (saveGeneratedFiles) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if (var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
Files.createDirectories(var3);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class");
}
Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}
return var4;
}
刚才说,代理类的每一个方法都会调用InvocationHandler。
这个InvocationHandler实例其实是Proxy类的一个属性。Proxy中的方法都是静态方法,只有这个属性不是静态的。
所有的代理类都继续Proxy类。
代理类的方法调用的都是父类的InvocationHandler属性。
这样也就知道了,为什么JDK的动态代理,被代理的类必须实现接口了。
因为代理类无法作为被代理类的子类。因为代理类已经继续了Proxy类,而Java中是不支持多继承的。