(一)
一直都想做一个通过注解打印日志的工具类,即只需要在方法上加一个注解,即可以打印出方法的参数及返回值,却一直没有好的思路。
最近在研究面向切面编程(AOP),意外发现了一个库【hugo-JakeWharton】,没错,就是鼎鼎大名的ButterKnife的作者JakeWharton。
真是踏破铁鞋无觅处,得来全不费工夫!
hugo的用法超级简单,这里不再赘述,想了解的同学点击链接查看官方文档即可。
hugo的介绍到这里就结束了,喜欢的同学自行尝试。
本文的重点是如何使用JDK的动态代理机制,实现一个对原方法无入侵性的日志打印工具类。
(二)
先介绍一下JDK的动态代理及其简单用法。
Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
// 使用动态代理创建对象
PersonInterface person = (PersonInterface) Proxy.newProxyInstance(
PersonInterface.class.getClassLoader(),
new Class[]{PersonInterface.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
// you code here...
return null; // method return value
}
});
JDK动态代理的入口类为Proxy
,利用Proxy#newProxyInstance(...)
方法,我们可以在运行时动态获取到类的的对象及类的方法对象,从而可以在方法运行前或运行后动态添加指定的代码。
利用JDK动态代理的这个特性,正好可以完美地实现日志打印功能。
注:动态代理的类要求必须实现了接口,否则无法代理。
(三)
以下为实现代码:
import android.util.Log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class LogProxy {
/**
* 在代理对象的方法的入口和出口分别打印日志
* 在方法入口处打印方法参数,在方法出口处打印返回值
*
* @param target 被代理的对象必须实现了某些接口。
* 1. 对于target直接实现的接口,可以使用target.getClass().getInterfaces()获取;
* 2. 对于target非直接实现的接口,需要通过方法参数传入。
*/
public static Object proxy(final Object target, final Class... interfaces) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
interfaces, // target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Log.i("Haoxueren", method.getName() + "() 参数:" + Arrays.toString(args));
Object result = method.invoke(target, args);
// Object result = method.invoke(proxy, args); // recursion
Log.i("Haoxueren", method.getName() + "() 返回值:" + result);
return result;
}
});
}
(四)
测试一下效果,不仅可以为我们自定义的类打印日志,还可以为系统类打印日志哦。
// 对于直接实现接口,直接传入对象即可
String string = "haoxueren";
CharSequence proxy = (CharSequence) LogProxy.proxy(string, target.getClass().getInterfaces());
proxy.length();
// 对于非直接实现的接口,需要手动声明(支持声明多个接口)
LifecycleOwner proxy = (LifecycleOwner) LogProxy.proxy(activity, LifecycleOwner.class);
proxy.getLifecycle();