java动态代理作用及源码分析
一、理解
- 静态代理:静态代理是在编译时就将接口、实现类、代理类一股脑儿全部手动完成
- 动态代理:在程序运行期间根据需要动态的创建代理类及其实例,来完成具体的功能
二、应用场景
- 参考装饰器模式,在已有的方法中进行再次封装,实现新增功能
- AOP面向切面编程思想
三、实现代码
在了解了动态代理之前,我们先通过最简单的例子看静态代理是如何实现的。
先定义一个接口
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public interface Subject {
public void doSomething();
}
完成一个该接口的实现类,并实现doSomething方法
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("call doSomething()");
}
}
假如这时有需求,需要改写doSomething方法,再方法执行前后增加日志打印功能,并计算该功能耗时,可是其中实现逻辑复杂<貌似并不复杂,只有一句打印,不要在意这些细节。>,不想修改原有代码,这时我们新建一个代理类,在其中实现我们需要的功能。
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class SubjectProxy implements Subject {
Subject subimpl = new RealSubject();
@Override
public void doSomething() {
System.out.println("我们先做点什么");
subimpl.doSomething();
System.out.println("我们再做点什么");
}
}
这个时候我们就可以利用新的代理类来实现新的需求,而不用修改源代码。下面完成测试类
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class TestStaticProxy {
public static void main(String args[]) {
// Subject sub = new RealSubject();
Subject sub = new SubjectProxy();
sub.doSomething();
}
}
好啦,这时候我们已经完成了需求人员的要求了。可是这个时候,老板又跳出来,说我想测试一下工程中多个类中方法的耗时。
干!我要新建多少个代理类啊。
这个时候动态代理就应运而生了。首先我们还是定义接口
package about_proxy.dynamic_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public interface Subject {
public void doSomething();
}
然后定义实现类
package about_proxy.dynamic_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("call doSomething()");
}
}
上面我们就完成了准备工作,接下来实现动态代理
package about_proxy.dynamic_proxy;
import org.omg.CORBA.portable.InvokeHandler;
import sun.rmi.runtime.Log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class ProxyHandler implements InvocationHandler {
private Object tar;
public Object bind(Object tar)
{
this.tar = tar;
//绑定该类实现的所有接口,取得代理类
return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
//这里就可以进行所谓的AOP编程了
//在调用具体函数方法前,执行功能处理
System.out.println("start time:"+System.currentTimeMillis());
result = method.invoke(tar,args);
//在调用具体函数方法后,执行功能处理
System.out.println("end time:"+System.currentTimeMillis());
return result;
}
}
最后再测试类中使用动态代理
package about_proxy.dynamic_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class TestDynamicProxy {
public static void main(String args[]){
// Subject sub = new RealSubject();
ProxyHandler proxy = new ProxyHandler();
//绑定该类实现的所有接口
Subject sub = (Subject) proxy.bind(new RealSubject());
sub.doSomething();
}
}
这样我们就可以在一个ProxyHandler实现多个代理类的功能(本demo只使用了一个动态代理),但是只创建了一个实体类。是如何实现的呢?动态代理其实为我们在运行期间动态生成了多个代理类,下面我们通过源码来了解一下jdk中是如何操作的。
四、原理简析
我们可以debug一下demo,当工程执行到doSomething()方法时进入了ProxyHandler类中的invoke方法,以实现了我们在真正的doSomething()方法前后增加了自己想要的功能。
为什么会进入invoke中呢?
在上述demo的main方法中调用了ProxyHandler的bind方法,
Subject sub = (Subject) proxy.bind(new RealSubject());
其实是调用了Proxy类的静态方法newProxyInstance()
Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
这里便是生成代理的关键了,我们继续跟进查看内部关键
@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);
}
/*
* 获取代理类。
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* 使用指定的invocationHandler调用构造方法
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//调用代理对象的构造函数(代理对象的构造函数$Proxy0(InvocationHandler h),通过字节码反编译可以查看生成的代理类)
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;
}
});
}
//生成代理类的实例,并把MyInvocationHander的实例作为构造函数参数传入
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)方法
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
//实现接口的最大数量<65535
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
//调用了get方法
return proxyClassCache.get(loader, interfaces);
}
继续跟入proxyClassCache.get(loader, interfaces);
/**
* @param key 上面传入的loader,类加载器
* @param parameter 上面方法传入的interfaces,接口数组
*/
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
// 返回的value是通过该方法调用的
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);
}
}
}
}
我们继续查看supplier.get()方法,该方法的实现在WeakCache的内部类Factory中,代码如下
@Override
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {
// 这里又通过valueFactory.apply(key, parameter)得到value进行返回
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed)
if (valuesMap.replace(subKey, this, cacheValue)) {
// put also in reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
} else {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
继续跟踪valueFactory.apply(key, parameter)方法,该方法的实现在Proxy的内部类ProxyClassFactory中
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* 确保该loader加载的此类(intf)
*/
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");
}
/*
* 确保是一个接口
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* 确保接口没重复
*/
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;
/*
* 验证所有非公共的接口在同一个包内;公共的就无需处理.
*/
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 + ".";
}
/*
* 为代理类生成一个名字,防止重复
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* 具体生成代理类的方法又在该方法中实现
*/
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(proxyName, interfaces, accessFlags)
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
//真正生成字节码的方法
final byte[] classFile = gen.generateClassFile();
//如果saveGeneratedFiles为true 则生成字节码文件,所以在开始我们要设置这个参数
//当然,也可以通过返回的bytes自己输出
if (saveGeneratedFiles) {
java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() {
public Void run() {
try {
int i = name.lastIndexOf('.');
Path path;
if (i > 0) {
Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
Files.createDirectories(dir);
path = dir.resolve(name.substring(i+1, name.length()) + ".class");
} else {
path = Paths.get(name + ".class");
}
Files.write(path, classFile);
return null;
} catch (IOException e) {
throw new InternalError( "I/O exception saving generated file: " + e);
}
}
});
}
return classFile;
}
继续跟生成自己码的代码,这里便是最终的生成方法了
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
* 步骤1:为所有方法生成代理调度代码,将代理方法对象集合起来。
*/
//增加 hashcode、equals、toString方法
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
//增加接口方法
for (Class<?> intf : interfaces) {
for (Method m : intf.getMethods()) {
addProxyMethod(m, intf);
}
}
/*
* 验证方法签名相同的一组方法,返回值类型是否相同;意思就是重写方法要方法签名和返回值一样
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
* 为类中的方法生成字段信息和方法信息
*/
try {
//增加构造方法
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
//增加静态初始化信息
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
* 步骤3:编写最终类文件
*/
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
* 在开始编写最终类文件之前,确保为下面的项目保留常量池索引。
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (Class<?> intf: interfaces) {
cp.getClass(dotToSlash(intf.getName()));
}
/*
* Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
* 设置只读,在这之前不允许在常量池中增加信息,因为要写常量池表
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 次要版本;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 主版本
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 访问标识;
dout.writeShort(accessFlags);
// u2 本类名;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 父类名;
dout.writeShort(cp.getClass(superclassName));
// u2 接口;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (Class<?> intf : interfaces) {
dout.writeShort(cp.getClass(
dotToSlash(intf.getName())));
}
// u2 字段;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 方法;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 类文件属性:对于代理类来说没有类文件属性;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
return bout.toByteArray();
}
上面对源码一顿分析,接下来我们将demo中调用bind方法中Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this)动态生成的代理类打印出来,修改我们的demo
package about_proxy.dynamic_proxy;
import sun.misc.ProxyGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by solie_h on 2018/2/7.
*/
public class TestDynamicProxy {
public static void main(String args[]){
// Subject sub = new RealSubject();
ProxyHandler proxy = new ProxyHandler();
//绑定该类实现的所有接口
Subject sub = (Subject) proxy.bind(new RealSubject());
// 将动态生成的代理类打印出来
// 这里需要修改为你需要输出的路径
String path = "请修改路径/TestProxy.class";
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0",RealSubject.class.getInterfaces());
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
out.write(classFile);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
sub.doSomething();
}
}
将生成的TestProxy.class文件反编译,这里给不熟悉反编译操作的同学提供一个在线反编译工具:http://www.javadecompilers.com/
import about_proxy.dynamic_proxy.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0
extends Proxy
implements Subject
{
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler paramInvocationHandler)
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
{
try
{
return ((Boolean)h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void doSomething()
{
try
{
h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString()
{
try
{
return (String)h.invoke(this, m2, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode()
{
try
{
return ((Integer)h.invoke(this, m0, null)).intValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m3 = Class.forName("about_proxy.dynamic_proxy.Subject").getMethod("doSomething", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
我们先来看该类的构造方法
public $Proxy0(InvocationHandler paramInvocationHandler)
{
super(paramInvocationHandler);
}
传入参数为InvocationHandler,这就是为什么动态代理类在调用接口中方法时会走到自定义的InvocationHandler中的invoke方法。
super(paramInvocationHandler),是调用父类Proxy的构造方法。而父类又持有protected InvocationHandler h的实例,参考Proxy的构造方法:
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
在继续看反编译出来文件的静态代码块
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m3 = Class.forName("about_proxy.dynamic_proxy.Subject").getMethod("doSomething", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
我们在接口中定义的方法doSomething通过反射得到的名字是m3,我们继续查看文件中实现的doSomething()方法
public final void doSomething()
{
try
{
h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
这里调用代理对象的doSomething方法,直接就调用了InvocationHandler中的invoke方法,并把m3传了进去。
this.h.invoke(this, m3, null);
其余的equals、toString、hashCode也是同样的道理。
到这里就很明了了,所有的动态代理流程也清晰了。
五、总结
JDK是动态生成代理类,并通过调用解析器,执行接口实现的方法的原理已经一目了然。动态代理加上反射,是很多框架的基础。期待下一章节实现根据动态代理与反射实现的android的注入框架原理解析。
个人见解,若有错误之处,欢迎指出更正
文章中demo放置在github
https://github.com/loosaSH/java-Proxy
参考文章:
1、Java帝国之动态代理(用故事形式讲解动态代理的出现及原理)
2、知乎-Java 动态代理作用是什么?
3、简书-动态代理
4、JDK8动态代理源码分析