说到动态代理的受限于的接口的,这包括两个方面
- 非接口不能使用JDK动态代理
- 若一个类实现了接口(implements), 其非接口定义的method也不能使用JDK动态代理
为何Cglib可以代理普通类,而JDK 动态代理的受限于接口的原因是什么?
先说结论,这是因为JDK 动态代理会生成一个新的类Proxy$N,这个类会直接继承java.lang.reflect.Proxy,起JDK源码为
package java.lang.reflect;
public class Proxy implements java.io.Serializable {
....
}
那么根据Java类的单继承语法,所有的类只能是单继承的,所以Proxy$N和被代理的对象的完全两个不同的实现类,压根不可能存在继承关系(代理对象不可能继承代理的对象).
但是这能解释JDK动态代理受限于接口么?
显然不可以,我们知道静态代理的代理对象和被代理的对象就没有接口限制这一说.
那么真的原因需要看源码.
我写了一个例子
public class JdkProxyTest {
class ProxyHandler implements InvocationHandler {
// 被代理的对象
private Object target;
public ProxyHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target, args);
}
}
@Test
void interfaceTest() {
//predicate是个匿名类的实例(Predicate是一个接口,这里用到lambda语法)
Predicate<Integer> predicate = it -> it > 100;
ProxyHandler handler = new ProxyHandler(predicate);
ClassLoader classLoader = predicate.getClass().getClassLoader();
Predicate proxy = (Predicate) Proxy.newProxyInstance(classLoader,
new Class[]{Predicate.class}, handler);
System.out.println(predicate.getClass() + "\t" + proxy.getClass());
System.out.println("result: \t" + proxy.test(50) + "\t" + proxy.test(500));
}
}
Proxy的方法 newProxyInstance,
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);
}
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;
}
});
}
//反射生成对象
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);
}
}
通过源码可以知道代理对象的是下面这行生成的
Class<?> cl = getProxyClass0(loader, intfs);
继续看源码
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// 代理的对象类通过缓存起来
return proxyClassCache.get(loader, interfaces);
}
看到这还是没看到代理的类是生成逻辑? Debug跟吧
line 124 是个循环
line 142 - 145 若cacha中没有生成代理类的supplier那么就将factory赋值给supplier并且从line142看到supplier放入到了cache中,下面看supplier(可以看到是WeakCache$Factory)的实现
我们看到com.lang.relect.Proxy$ProxyClassFactory的apply()方法实现了代理类
/**
* 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
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@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());
}
}
}
apply方法实现了
- 若不是接口类型,抛出异常, 这儿从代码层面印证JDK动态代理受限于接口
- 生成代理类的名称
- 生成代理类(class)的二进制流
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
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;
}
这个方法主要是
- 调用方法实现代理类class文件生成
- 保存class文件
private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));
若需要保存文件,在添加JVM参数: -Dsun.misc.ProxyGenerator.saveGeneratedFiles=true
生成的文件格式如下:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.sun.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.function.Predicate;
public final class $Proxy9 extends Proxy implements Predicate {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m6;
private static Method m4;
private static Method m5;
private static Method m7;
private static Method m0;
public $Proxy9(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final Predicate negate() throws {
try {
return (Predicate)super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final Predicate and(Predicate var1) throws {
try {
return (Predicate)super.h.invoke(this, m6, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final Predicate isEqual(Object var1) throws {
try {
return (Predicate)super.h.invoke(this, m4, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final boolean test(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m5, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final Predicate or(Predicate var1) throws {
try {
return (Predicate)super.h.invoke(this, m7, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("java.util.function.Predicate").getMethod("negate");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m6 = Class.forName("java.util.function.Predicate").getMethod("and", Class.forName("java.util.function.Predicate"));
m4 = Class.forName("java.util.function.Predicate").getMethod("isEqual", Class.forName("java.lang.Object"));
m5 = Class.forName("java.util.function.Predicate").getMethod("test", Class.forName("java.lang.Object"));
m7 = Class.forName("java.util.function.Predicate").getMethod("or", Class.forName("java.util.function.Predicate"));
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
可以清晰的看到代理为 com.sun.proxy.$Proxy9,继承了java.lang.reflect.Proxy,实现了
java.util.function.Predicate接口,并且所有的方法的实现均掉用super.h属性(InvocationHandler)这个对象就Proxy.newProxyInstance()的是否传递进来的(看Proxy源码确实有属性InvocationHandler h)
那么就清楚了所谓的动态的最终的实现思想生成若干的静态代理类(思想
归根溯源还是静态代理)
下面是com.sun.proxy.$Proxy9实现细节 还是sum.misc.ProxyGenerator类
private byte[] generateClassFile() {
this.addProxyMethod(hashCodeMethod, Object.class);
this.addProxyMethod(equalsMethod, Object.class);
this.addProxyMethod(toStringMethod, Object.class);
Class[] var1 = this.interfaces;
int var2 = var1.length;
int var3;
Class var4;
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
Method[] var5 = var4.getMethods();
int var6 = var5.length;
for(int var7 = 0; var7 < var6; ++var7) {
Method var8 = var5[var7];
this.addProxyMethod(var8, var4);
}
}
Iterator var11 = this.proxyMethods.values().iterator();
List var12;
while(var11.hasNext()) {
var12 = (List)var11.next();
checkReturnTypes(var12);
}
Iterator var15;
try {
this.methods.add(this.generateConstructor());
var11 = this.proxyMethods.values().iterator();
while(var11.hasNext()) {
var12 = (List)var11.next();
var15 = var12.iterator();
while(var15.hasNext()) {
ProxyGenerator.ProxyMethod var16 = (ProxyGenerator.ProxyMethod)var15.next();
this.fields.add(new ProxyGenerator.FieldInfo(var16.methodFieldName, "Ljava/lang/reflect/Method;", 10));
this.methods.add(var16.generateMethod());
}
}
this.methods.add(this.generateStaticInitializer());
} catch (IOException var10) {
throw new InternalError("unexpected I/O Exception", var10);
}
if (this.methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
} else if (this.fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
} else {
this.cp.getClass(dotToSlash(this.className));
this.cp.getClass("java/lang/reflect/Proxy");
var1 = this.interfaces;
var2 = var1.length;
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
this.cp.getClass(dotToSlash(var4.getName()));
}
this.cp.setReadOnly();
ByteArrayOutputStream var13 = new ByteArrayOutputStream();
DataOutputStream var14 = new DataOutputStream(var13);
try {
var14.writeInt(-889275714);
var14.writeShort(0);
var14.writeShort(49);
this.cp.write(var14);
var14.writeShort(this.accessFlags);
var14.writeShort(this.cp.getClass(dotToSlash(this.className)));
var14.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));
var14.writeShort(this.interfaces.length);
Class[] var17 = this.interfaces;
int var18 = var17.length;
for(int var19 = 0; var19 < var18; ++var19) {
Class var22 = var17[var19];
var14.writeShort(this.cp.getClass(dotToSlash(var22.getName())));
}
var14.writeShort(this.fields.size());
var15 = this.fields.iterator();
while(var15.hasNext()) {
ProxyGenerator.FieldInfo var20 = (ProxyGenerator.FieldInfo)var15.next();
var20.write(var14);
}
var14.writeShort(this.methods.size());
var15 = this.methods.iterator();
while(var15.hasNext()) {
ProxyGenerator.MethodInfo var21 = (ProxyGenerator.MethodInfo)var15.next();
var21.write(var14);
}
var14.writeShort(0);
return var13.toByteArray();
} catch (IOException var9) {
throw new InternalError("unexpected I/O Exception", var9);
}
}
}
回到上面的问题, 为什么静态代理不受限与接口而JDK 动态代理要首先呢?
是因为JDK 在实现的时候需哪些方法?是根据传递接口确定的,所以代理类是不会有被代理类非接口(hascode, euqals等除外,因为这些是object基本方法,任何对象都会有),上面说了Java单继承的语法也是一个原因
总之: JDK 动态代理的实现方案和Java单继承的语法导致了这个限制的存在.
还有个问题吗,动态代理类(Class)每次都要重新生成一遍吗?
不是的:
再次获取动态代理的的时候,supplier变成了WeakChache$CacheValue(本文上面说过首次生成的时候supplier是WeakCache$Factory),直接返回,不会重新生成一遍
那是什么时候放进去的呢?
WeakCache.Factory的get()方法在
line240-243代理类的缓存逻辑