Introduction to AspectJ for Android Development and Gradle Plugin Integration
This article provides a comprehensive guide to using AspectJ for aspect‑oriented programming in Android, covering core concepts such as aspects, join points, pointcuts and advice, demonstrating matching expressions, custom annotations, and detailing step‑by‑step integration with Gradle plugins and plugin implementation for seamless code weaving.
AspectJ is an implementation of Aspect‑Oriented Programming (AOP) for the Java language. It can be used in two ways: by writing Java annotations and letting the AspectJ weaver weave the code into the target class files, or by writing AspectJ source files and compiling them with the ajc compiler. Because Android Studio does not support the AspectJ syntax directly, Android development typically uses the annotation‑based approach.
Basic Concepts
1. Aspect – An independent unit of functionality that can be applied to multiple classes. Example:
@Aspect
public class SampleAspect {
@Pointcut("execution(void android.support.v4.app.FragmentActivity+.onCreate(..))")
public void activityOnCreate() {}
@Around("activityOnCreate()")
public Object activityOnCreateTime(ProceedingJoinPoint joinPoint) {
Object object = null;
long startTime = System.currentTimeMillis();
try {
object = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Log.d("chao", "activityOnCreateTime:" + (System.currentTimeMillis() - startTime));
return object;
}
}2. JoinPoint – Represents a point in the program where code can be inserted, such as method execution, class initialization, or exception handling.
3. Pointcut – Defines the specific join points to which advice should be applied. Example:
@Pointcut("execution(void android.support.v4.app.FragmentActivity+.onCreate(..))")
public void activityOnCreate() {}4. Advice – The code that runs at a pointcut. Types include @Before, @After, and @Around. Example:
@Around("activityOnCreate()")
public Object activityOnCreateTime(ProceedingJoinPoint joinPoint) { /* ... */ }
@Before("activityOnCreate()")
public void onCreateBefore(JoinPoint joinPoint) { /* ... */ }
@After("activityOnCreate()")
public void onCreateAfter(JoinPoint joinPoint) { /* ... */ }Matching Expressions
AspectJ provides a rich syntax for defining pointcuts. Method‑type expressions use the execution() keyword, and optional modifiers such as annotations, visibility, static, final, return type, class name, method name, and parameter list. Operators like !, &&, and || can combine expressions. Special symbols such as + (self and subclasses), * (any type), and .. (any length) are also supported.
Examples of complex pointcuts:
@Pointcut("execution(@com.sohu.aspectj.AspectLog * *(..)) && @annotation(hyaspect)")
public void method(AspectLog hyaspect) { }
@Pointcut("handler(java.lang.Exception) && within(com.sohu.aspectj.*)")
public void fragmentException() { }Custom Annotations
Define a custom annotation to mark methods that need weaving:
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AspectLog {
String[] checkString();
int checkCode();
}Apply the annotation:
@AspectLog(checkCode = 3, checkString = {"a", "b", "b"})
public void execute(String out) { /* ... */ }In the aspect, retrieve annotation values either via @annotation() or by reflecting on the ProceedingJoinPoint:
@Around("method(hyaspect) || constructor(hyaspect)")
public Object logAndExecute(ProceedingJoinPoint joinPoint, AspectLog hyaspect) throws Throwable {
String[] checkString = hyaspect.checkString();
Log.d("chao", "-----AspectLog:needCheck:" + hyaspect.needCheck() + " checkCode:" + hyaspect.checkCode() + " checkString:" + checkString[0]);
// additional logging of class, method, parameters, execution time, etc.
Object result = joinPoint.proceed();
return result;
}
@Around("method2() || constructor2()")
public Object logAndExecute2(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
AspectLog hyaspect = methodSignature.getMethod().getAnnotation(AspectLog.class);
// use hyaspect values
Object result = joinPoint.proceed();
return result;
}Using AspectJ in Android
Three steps are required:
Add the AspectJ runtime dependency to the module that contains aspects: implementation 'org.aspectj:aspectjrt:1.8.7' Integrate a Gradle plugin that runs the AspectJ weaver after Java compilation. Since there is no official plugin, you can either write a custom plugin or use a third‑party one.
Write aspect classes, define pointcuts and advice, and configure the plugin to weave the code.
Example Gradle plugin implementation (custom plugin module buildSrc):
apply plugin: 'groovy'
repositories {
mavenLocal()
jcenter()
google()
}
dependencies {
implementation gradleApi()
implementation localGroovy()
implementation 'org.aspectj:aspectjtools:1.8.7'
implementation 'com.android.tools.build:gradle:3.2.1'
implementation 'org.aspectj:aspectjrt:1.8.7'
}Plugin class:
class HyAspectJPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.extensions.getByType(AppExtension).getApplicationVariants().all { variant ->
JavaCompile javaCompiler = variant.javaCompiler
javaCompiler.doLast {
String[] args = [
"-showWeaveInfo",
"-1.7",
"-inpath", javaCompile.destinationDir.toString(),
"-aspectpath", javaCompiler.classpath.asPath,
"-d", javaCompile.destinationDir.toString(),
"-classpath", javaCompiler.classpath.asPath,
"-bootclasspath", javaCompile.options.bootstrapClasspath.asPath
]
MessageHandler handler = new MessageHandler(true)
new Main().run(args, handler)
// log messages from handler
}
}
}
}Configure the plugin by creating
resources/META-INF/gradle-plugins/com.sohu.aspectj.propertieswith the line implementation-class=com.sohu.aspectj.HyAspectJ.
Advanced Gradle Plugin
A more robust third‑party plugin registers a Transform, captures both Java and Kotlin class files, filters the classes that need weaving, and performs asynchronous weaving. This plugin supports Instant Run, configurable weaving scopes, Kotlin code, and asynchronous processing.
References and further reading are listed at the end of the original article.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
