读前须知:
动态代理:只有你在运行的时候,才会产生代理类(代理对象),这个代理对象是动态生成的。我们在实现动态代理的时候,代理类并不像静态代理一样真正的创建一个class文件一个代理类,那么jdk是怎么实现动态代理的呢?
类完整的生命周期.png
我们知道在jdk里面,首先我们会写一个java源文件(.java文件),然后他会编译成对应.class文件(字节码),class文件在我们实际运行的时候,java虚拟机会通过类加载器把它加载出一个class对象,通过class对象再拿到各自实例对象(实例化),然后我们就可以通过这个对象调用各自方法了。
然而在动态代理的时候,对我们动态代理类来讲是没有写java源文件(java文件)这一步的,那么jdk是如何实现的呢?其实,说穿了,在jdk里面,任何可以执行的一定是java字节码,当我们编译好了之后,就会生成.class文件,字节码就是01二进制串,可以放在硬盘里也可以放在内存里,甚至可以网上传递过来。那么动态代理是怎么创建代理类的呢?
我们通过打断点发现,动态代理会生成一个$Proxy0对象,
image那么个$Proxy0到底是怎么生成的呢?我们进入初始化方法Proxy.newProxyInstance方法看下
@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);
}
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);
}
}
在newProxyInstance方法里我们看到Class<?> cl = getProxyClass0(loader, intfs);这个方法应该就是通过反射拿到Proxy的Class对象,再通过Constructor<?> cons = cl.getConstructor(constructorParams);拿到c1的构造方法,我们再进到getProxyClass0方法里看下是怎么拿到class对象的
/**
* 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);
}
这段代码里我们直接看到return proxyClassCache.get(loader, interfaces);很显然class对象是在这里拿到了的,字面意思我们才到就是从java的缓存里通过类加载器和接口拿到class对象,所以我们再点击get方法里看看
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
if (value != null) {
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
get是一个范型方法,前面一部分是从缓存map里根据可以取值,后面一部分我们注意到这段代码
一开始通过requireNonNull生成一个subKey,然后通过subKey从map里拿到一个Supplier<V> 数组,V就是这个get方法的类型,然后再从Supplier<V> 数组supplier里拿到最终值value,如果value!=null再返回。所以关键的地方应该就是requireNonNull这个方法,我们点进去发现
image.png
这里并没有真正实现的代码,所以我们注意到subKeyFactory.apply(key, parameter)这个方法,它是一个范型接口里的一个方法,所以我们查看apply这个方法的实现
image.png
我们进入最后一个看看
@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());
}
}
前面也是一大堆反射,我们注意到
image.png
从它注释Generate the specified proxy class,我们也可以确定他就是真正生成代理对象的地方,这里通过ProxyGenerator.generateProxyClass生成一个byte数组,然后再return一个defineClass0(loader, proxyName,proxyClassFile, 0,proxyClassFile.length);我们知道java里的.class文件实际上是有许多byte字节码组成的,所以我们猜测这里就是真正生成class对象的地方,defineClass0方法就是把字节数组转化为实际class的方法,我们点进去发现是一个native
native在java里应该就是C++代码来实现的。
那么我们之前打断点的$Proxy0是怎么来的呢?
我们注意到这里的注释Choose a name for the proxy class to generate.选择一个名字给代理class,我们点进去 image.png
这里的proxyClassNamePrefix是不是就是我们断点打出来的代理类的名字么,后面+num我们不用猜,肯定就是0,1,2,3。。。这样的num。那么ProxyGenerator.generateProxyClass
怎么生成byte数组的呢?我们点进去,
image.png
从注释里可以看到,是系统编译器直接创建的,大致浏览下代码,就是各种IO操作,我猜测应该就是读写.class文件里的操作,文章最后我们会去揭秘。
所以我们最后得出结论,动态代理调用newProxyInstance的时候,jdk会在内部通过各种反射,生成一个字节数组,然后通过defineClass0把字节数组转换成class文件,有了class文件之后,就像文章开头讲的一样,通过class对象再拿到各自实例对象(实例化),然后我们就可以通过这个对象调用各自方法了。
- 最后我们来研究下 byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);到底是怎么实现的呢?
这里最后生成的是 byte[] proxyClassFile字节数组,那我们把ProxyGenerator.generateProxyClass拷出来自己去生成不就好了么?
具体生成代码如下:
byte[] proxyClassFile =ProxyGenerator.generateProxyClass(
proxyName, new Class[]{clazz});
String paths = clazz.getResource(".").getPath();
System.out.println(paths);
FileOutputStream out = null;
try {
out = new FileOutputStream(paths+proxyName+".class");
out.write(proxyClassFile);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
image.png
image.png
我们找到这个目录,看到一个$Proxy0.class,
image.png
我们再用java反编译工具打开
image.png
代码如下
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import proxy.FruitFactory;
public final class $Proxy0 extends Proxy implements FruitFactory {
private static Method m1;
private static Method m8;
private static Method m2;
private static Method m3;
private static Method m5;
private static Method m4;
private static Method m7;
private static Method m9;
private static Method m0;
private static Method m6;
public $Proxy0(InvocationHandler paramInvocationHandler) {
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject) {
try {
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void notify() {
try {
this.h.invoke(this, m8, null);
return;
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString() {
try {
return (String)this.h.invoke(this, m2, null);
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void saleFruit(int paramInt) {
try {
this.h.invoke(this, m3, new Object[] { Integer.valueOf(paramInt) });
return;
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void wait(long paramLong) throws InterruptedException {
try {
this.h.invoke(this, m5, new Object[] { Long.valueOf(paramLong) });
return;
} catch (Error|RuntimeException|InterruptedException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void wait(long paramLong, int paramInt) throws InterruptedException {
try {
this.h.invoke(this, m4, new Object[] { Long.valueOf(paramLong), Integer.valueOf(paramInt) });
return;
} catch (Error|RuntimeException|InterruptedException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final Class getClass() {
try {
return (Class)this.h.invoke(this, m7, null);
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void notifyAll() {
try {
this.h.invoke(this, m9, null);
return;
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final int hashCode() {
try {
return ((Integer)this.h.invoke(this, m0, null)).intValue();
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void wait() throws InterruptedException {
try {
this.h.invoke(this, m6, null);
return;
} catch (Error|RuntimeException|InterruptedException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m8 = Class.forName("proxy.FruitFactory").getMethod("notify", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m3 = Class.forName("proxy.FruitFactory").getMethod("saleFruit", new Class[] { int.class });
m5 = Class.forName("proxy.FruitFactory").getMethod("wait", new Class[] { long.class });
m4 = Class.forName("proxy.FruitFactory").getMethod("wait", new Class[] { long.class, int.class });
m7 = Class.forName("proxy.FruitFactory").getMethod("getClass", new Class[0]);
m9 = Class.forName("proxy.FruitFactory").getMethod("notifyAll", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m6 = Class.forName("proxy.FruitFactory").getMethod("wait", new Class[0]);
return;
} catch (NoSuchMethodException noSuchMethodException) {
throw new NoSuchMethodError(noSuchMethodException.getMessage());
} catch (ClassNotFoundException classNotFoundException) {
throw new NoClassDefFoundError(classNotFoundException.getMessage());
}
}
}
从上面的代码可以看出我们创建的动态代理类是派生自Proxy,并且实现了
FruitFactory接口
image.png
image.png
这是接口里的方法,他这里就是通过反射来实现这个方法的,这个h就是Proxy里的InvocationHandler
image.png
在$Proxy0.class里,我们可以看出来,这个class实际功能就和静态代理的代理类是一样的,只是jdk在内部帮我们去动态实现了这个代理类。
最后总结:
- 动态代理
是指在使用时再创建代理类和实例 - 优点
只需要1个动态代理类就可以解决创建多个静态代理的问题,避免重复、多余代码
更强的灵活性 - 缺点
效率低,相比静态代理中 直接调用目标对象方法,动态代理则需要先通过Java反射机制 从而 间接调用目标对象方法 - 应用场景局限,因为 Java 的单继承特性(每个代理类都继承了 Proxy 类),即只能针对接口 创建 代理类,不能针对类创建代理类。
在java的动态代理机制中,有两个重要的类或接口,一个是InvocationHandler接口、另一个则是 Proxy类,这个类和接口是实现我们动态代理所必须用到的。
网友评论