要在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方法執行前后分別打印日志。