要在Android中使用AspectJ,需要进行以下步骤:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.aspectj:aspectjtools:1.8.10'
}
}
apply plugin: 'com.android.application'
android {
...
}
dependencies {
...
}
apply plugin: 'android-aspectj'
apply from: 'aspectj.gradle'
@Aspect
public class MyAspect {
@Pointcut("execution(* com.example.myapp.MainActivity.onCreate(..))")
public void onCreatePointcut() {}
@Before("onCreatePointcut()")
public void beforeOnCreate(JoinPoint joinPoint) {
Log.d("AspectJ", "Before onCreate");
}
@After("onCreatePointcut()")
public void afterOnCreate(JoinPoint joinPoint) {
Log.d("AspectJ", "After onCreate");
}
}
<application
...
<meta-data
android:name="org.aspectj.weaver.loadtime.Agent"
android:value="org.aspectj.weaver.loadtime.StdlibAdaptor" />
...
</application>
以上步骤将在MainActivity的onCreate方法执行前后分别打印日志。