Mobile Development 15 min read

Using Annotation Processing Tool (APT) for Automated Code Generation in Android Development

This article explains the concept and practical application of the Annotation Processing Tool (APT) in Android development, demonstrating how to set up an APT project, define annotations, process them with custom processors, and automatically generate Java code for activity navigation using JavaPoet.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Using Annotation Processing Tool (APT) for Automated Code Generation in Android Development

APT (Annotation Processing Tool) is a built‑in compiler tool that scans and processes annotations during the Java compilation phase. It enables developers to generate repetitive boilerplate code automatically, improving readability and reducing manual effort. Popular libraries such as ButterKnife and GreenDAO already leverage APT.

The article uses a common Android activity‑navigation scenario to illustrate APT usage, covering project setup, annotation definition, processor implementation, data extraction, and code generation with JavaPoet.

1. Project Setup

Create an Android Library to hold custom annotations, then add a Java Library that depends on it. Register the annotation processor using the auto-service library or manual META‑INF services registration.

Example Gradle dependency:

implementation 'com.google.auto.service:auto-service:1.0-rc2'

For Kotlin projects use kapt instead of annotationProcessor: kapt project(':libProce') 2. Define an Annotation

@Retention(CLASS)
@Target(FIELD)
public @interface AutoBundle {
    boolean require() default false;
}

3. Implement the Processor

@AutoService(Processor.class)
public class AutoBundleProcessor extends AbstractProcessor {
    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) { /* ... */ }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { /* ... */ }

    @Override
    public Set<String> getSupportedAnnotationTypes() { return Collections.singleton(AutoBundle.class.getCanonicalName()); }
}

Inside process, retrieve elements annotated with @AutoBundle:

for (Element element : roundEnvironment.getElementsAnnotatedWith(AutoBundle.class)) {
    // handle each field
}

For each VariableElement, obtain the field name, type, package, class name, and annotation values:

String className = typeElement.getSimpleName().toString();
String packageName = elements.getPackageOf(typeElement).getQualifiedName().toString();
AutoBundle autoBundle = variableElement.getAnnotation(AutoBundle.class);
boolean require = autoBundle.require();
Name name = variableElement.getSimpleName();
TypeMirror type = variableElement.asType();

4. Generate Code with JavaPoet

JavaPoet simplifies building Java source files. Use TypeSpec for classes, MethodSpec for methods, and FieldSpec for fields.

TypeSpec.Builder contentBuilder = TypeSpec.classBuilder("YourClassName");
MethodSpec.Builder buildMethodBuilder = MethodSpec.methodBuilder("build")
        .addModifiers(Modifier.PUBLIC)
        .returns(ClassName.get("android.content", "Intent"));
buildMethodBuilder.addParameter(ClassName.get("android.content", "Context"), "context");
buildMethodBuilder.addStatement("Intent intent = new Intent(context, $L.class)", className);
// add putExtra statements for each field
buildMethodBuilder.addStatement("return intent");
contentBuilder.addMethod(buildMethodBuilder.build());

Write the generated file to the compiler's Filer:

JavaFile javaFile = JavaFile.builder(packageName, contentBuilder.build()).build();
try {
    javaFile.writeTo(filer);
} catch (IOException e) {
    e.printStackTrace();
}

5. Resulting Generated Code

public Intent build(Context context) {
    Intent intent = new Intent(context, TestActivity.class);
    intent.putExtra("id", id);
    intent.putExtra("name", name);
    intent.putExtra("is", is);
    if (!(context instanceof Activity)) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    return intent;
}

And a binding method to read the extras back into the activity:

public void bind(TestActivity target, Intent intent) {
    target.id = intent.getIntExtra("id", 0);
    target.name = intent.getStringExtra("name");
    target.is = intent.getBooleanExtra("is", false);
}

The article concludes with a flow diagram summarizing the entire APT development process, from annotation definition to automatic Java file generation, demonstrating how APT can streamline Android codebases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

mobile developmentCode GenerationAndroidAnnotation ProcessingJavaPoet
Sohu Tech Products
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.