初次接触动态代理是在学习Android插件化原理的时候,其中有一个步骤是通过hook AMS来实现应用启动过程中的“偷梁换柱”,将插件activity替换代理activity。接下来从一个例子讲解,动态代理能做什么:
interface IHello {
void hello();
}
static class Hello implements IHello {
@Override
public void hello() {
System.out.println("hello : "+getClass().getName());
}
}
上面定义了一个接口IHello和一个实现类Hello,接下来要在调用hello()方法的时候动态添加一个接口被调用的打印:
@Test
public void main() {
IHello hello = new Hello();
LogHandler handler = new LogHandler(hello);
IHello proxy = (IHello) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
hello.getClass().getInterfaces(),
handler);
proxy.hello();
Class<?> superClass = proxy.getClass().getSuperclass();
if (superClass != null) {
System.out.println(superClass.getName());
}
}
static class LogHandler implements InvocationHandler {
private Object object;
public LogHandler(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
System.out.println("--------------------invoke start--------------------");
Object res = method.invoke(object,args);
System.out.println("-------------------- invoke end --------------------");
return res;
}
}
输出结果:
==============================================
java.lang.reflect.Proxy
--------------------invoke start--------------------
hello : com.test.ExampleTest$Hello
-------------------- invoke end --------------------
==============================================
上面定义了LogHandler实现了InvocationHandler接口,然后通过Proxy.newProxyInstance获取代理的接口对象,最后通过接口对象调用hello方法,在LogHandler构造中传入了Hello对象,在invoke函数中我们可以看到,它是通过反射调用的Hello对象的hello()方法。对于使用者来说,代理类是动态生成的,但在实际运行中,内存中生成了一个新的类,这个类在调用hello()方法实际是调用的LogHandler的invoke()方法,而在invoke()方法中实现了真正的方法调用。
从上面可以看到,动态代理的核心方法就是Proxy.newProxyInstance,接下来分析它的源码:
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
// InvocationHandler对象不能为空
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
// Android-removed: SecurityManager calls
/*
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
*/
/*
* 查找或生成指定的代理类
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
// Android-removed: SecurityManager / permission checks.
/*
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
*/
// 获取构造方法
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
// BEGIN Android-removed: Excluded AccessController.doPrivileged call.
/*
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
*/
// 如果不是public需要setAccessible
cons.setAccessible(true);
// END Android-removed: Excluded AccessController.doPrivileged call.
}
// 返回代理对象
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);
}
}
// 生成代理类
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
// 方法数不能大于65535
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// 从缓存中获取对象
return proxyClassCache.get(loader, interfaces);
}
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
从上面可以看到newProxyInstance中有三个参数,一个ClassLoader,一个接口,以及一个InvocationHandler对象,通过getProxyClass0获取代理类,代理类从缓存proxyClassCache获取,这是一个WeakCache对象,在构造的时候传入了KeyFactory,ProxyClassFactory两个对象,查看源码:
private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
= new ConcurrentHashMap<>();
private final BiFunction<K, P, ?> subKeyFactory;
private final BiFunction<K, P, V> valueFactory;
public WeakCache(BiFunction<K, P, ?> subKeyFactory,
BiFunction<K, P, V> valueFactory) {
this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
this.valueFactory = Objects.requireNonNull(valueFactory);
}
public V get(K key, P parameter) {
// 判断Class<?>是否为空,这里的key是ClassLoader对象
Objects.requireNonNull(parameter);
// 删除过时的条目
expungeStaleEntries();
// 将key与refQueue绑定
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
// 如果map中没有保存key的value,那么为它新建一个ConcurrentHashMap作为值
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;
}
}
// 创建key
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
// 这个循环很有意思,如果第一次进来supplier不为null,那么get它的值
// supplier为空的时候则跳过,在赋值过后循环回到这里,返回get的值
if (supplier != null) {
// 调用Factory 的 get方法
V value = supplier.get();
if (value != null) {
return value;
}
}
// 创建一个Factory对象
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
// supplier为空,那么保存factory到valuesMap,并赋值到supplier
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);
}
}
}
}
private final class Factory implements Supplier<V> {
Factory(K key, P parameter, Object subKey,
ConcurrentMap<Object, Supplier<V>> valuesMap) {
this.key = key;
this.parameter = parameter;
this.subKey = subKey;
this.valuesMap = valuesMap;
}
@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,这是最终保存的值,它是由valueFactory创建,valueFactory是在构造函数中传进来ProxyClassFactory对象
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;
}
}
从上面可以看到,代理类的生成则是在ProxyClassFactory方法,查看其源码:
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; // 代理类的包名
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 the default package.
proxyPkg = "";
}
{
// Android-changed: Generate the proxy directly instead of calling
// through to ProxyGenerator.
List<Method> methods = getMethods(interfaces);
Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
validateReturnTypes(methods);
List<Class<?>[]> exceptions = deduplicateAndGetExceptions(methods);
Method[] methodsArray = methods.toArray(new Method[methods.size()]);
Class<?>[][] exceptionsArray = exceptions.toArray(new Class<?>[exceptions.size()][]);
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
// 代理类由包名+$Proxy+数字组成
String proxyName = proxyPkg + proxyClassNamePrefix + num;
return generateProxy(proxyName, interfaces, loader, methodsArray,
exceptionsArray);
}
}
}
从上面可以看到,代理类由ProxyClassFactory调用native方法generateProxy生成,其包名则是由包名+$Proxy+数字组成。从测试用例的输出结果可以看到代理类继承于java.lang.reflect.Proxy,故需要动态代理的类要提供一个接口实现,从而建立与代理类的联系。
还有InvocationHandler调用invoke的内容待发掘。