初次接触动态代理是在学习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() {
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[], Class>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
从上面可以看到newProxyInstance中有三个参数,一个ClassLoader,一个接口,以及一个InvocationHandler对象,通过getProxyClass0获取代理类,代理类从缓存proxyClassCache获取,这是一个WeakCache对象,在构造的时候传入了KeyFactory,ProxyClassFactory两个对象,查看源码:
private final ConcurrentMap
从上面可以看到,代理类的生成则是在ProxyClassFactory方法,查看其源码:
private static final class ProxyClassFactory
implements BiFunction[], 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, 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 methods = getMethods(interfaces);
Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
validateReturnTypes(methods);
List[]> 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的内容待发掘。