我有一个非常简单的 AspectJ 方面(使用 @AspectJ),它只打印出一条日志消息。我的目标是在我的 Android 应用程序中提供建议代码。现在,只要我的应用程序源代码中有方面类本身,这个方面就可以完美地工作。一旦我将方面移动到不同的模块(java -> .jar 或 android lib -> .aar),我会收到以下运行时异常在我的应用程序中运行建议的代码时:
java.lang.NoSuchMethodError: com.xxx.xxx.TraceAspect.aspectOf
基本上我的结构是这样的:
Root
+ app (com.android.application)
- MainActivity (with annotation to be adviced)
+ library (android-library)
- TraceAspect (aspect definition)
从 ajc 编译器中,我可以看到 ajc 编译器选择了我的类并正确地建议它们,所以我真的不知道为什么只要我的源代码中有 @AspectJ 类它就可以工作,但是一旦我移动就停止工作将其保存到 jar 存档中。
我正在使用 gradle。我的应用程序的构建脚本非常简单。我按照中的说明进行操作http://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/
import com.android.build.gradle.LibraryPlugin
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.+'
classpath 'org.aspectj:aspectjtools:1.8.1'
}
}
apply plugin: 'com.android.application'
repositories {
mavenCentral()
}
dependencies {
compile 'org.aspectj:aspectjrt:1.8.1'
compile project (':library')
}
android.applicationVariants.all { variant ->
AppPlugin plugin = project.plugins.getPlugin(AppPlugin)
JavaCompile javaCompile = variant.javaCompile
javaCompile.doLast {
String[] args = ["-showWeaveInfo",
"-1.5",
"-XnoInline",
"-inpath", javaCompile.destinationDir.toString(),
"-aspectpath", javaCompile.classpath.asPath,
"-d", javaCompile.destinationDir.toString(),
"-classpath", javaCompile.classpath.asPath,
"-bootclasspath", plugin.project.android.bootClasspath.join(File.pathSeparator)]
MessageHandler handler = new MessageHandler(true);
new Main().run(args, handler)
def log = project.logger
for (IMessage message : handler.getMessages(null, true)) {
switch (message.getKind()) {
case IMessage.ABORT:
case IMessage.ERROR:
case IMessage.FAIL:
log.error message.message, message.thrown
break;
case IMessage.WARNING:
log.warn message.message, message.thrown
break;
case IMessage.INFO:
log.info message.message, message.thrown
break;
case IMessage.DEBUG:
log.debug message.message, message.thrown
break;
}
}
}
}
不确定是否重要,但以防万一,我方面的代码:
@Aspect
public class TraceAspect {
private static final String POINTCUT_METHOD = "execution(@com.xxx.TraceAspect * *(..))";
@Pointcut(POINTCUT_METHOD)
public void annotatedMethod() {}
@Around("annotatedMethod()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Aspect works...");
return joinPoint.proceed();
}
}
类路径
我还检查了javaCompile.classPath
并且它正确地包含library-classes.jar
and my app-classes.jar
。添加-log file
to the ajc
任务还显示文件已正确编织。
有任何想法吗?
重现此问题的最小示例
https://github.com/fschoellhammer/test-aspectj