使用 AspectJ 在 android 中拦截第三方函数

Intercepting third party functions in android using AspectJ

我一直在尝试使用 aspectJ 拦截属于我的应用程序一部分的所有第三方函数,但不知何故我只能拦截我声明的函数,而不是第三方库声明的函数。

我正在使用引用自 this tutorial 的 aspectJ gradle 配置。

这是我的外观:

private static final String POINTCUT_METHOD = "execution(* *(..))";

@Pointcut(POINTCUT_METHOD) 
public void methodAnnotatedWithDebugTrace() {}

@Around("methodAnnotatedWithDebugTrace()") 
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) 
            throws Throwable { 
    // ...
}

有什么方法可以让我们也开始拦截第三方函数吗??

转述已多次给出的另一个答案:

You can only weave your own code

基本上 android 方面仅在编译时有效,通常会编写您自己的代码。如果您使用的是没有源代码的现有代码(例如 Android 框架),编译器将无权修改这些代码。在您的情况下,您只能在代码访问第三方库时捕获。

意味着如果你想拦截第三方库你需要使用"call(* *(..))"而不是"execution(* *(..))"

你可以用my gradle-aspectj plugin编织第三方库的代码。 这是可能的,因为 Transform API 处理所有项目源,不仅是 src/* 包,还有 jars/aars 子模块。 但要小心使用第三方代码编织,它可能会导致意外行为。