Fundamentals 5 min read

Using Compile-Time Java Annotations and Writing a Custom Annotation Processor

This article explains how Java annotations can be leveraged not only at runtime via reflection but also during compilation by creating custom annotation processors, illustrating the definition of an annotation, implementing a processor, configuring SPI, and demonstrating error handling with Maven.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Using Compile-Time Java Annotations and Writing a Custom Annotation Processor

Java annotations are encountered constantly, especially in Spring projects, where runtime annotations combined with reflection (e.g., @Autowired , @Value ) simplify many features.

Beyond runtime, annotations can be processed at compile time to enforce rules or generate code, as demonstrated by tools like Lombok and Google Auto.

The article shows how to define a custom annotation that must be used only once; applying it multiple times triggers a compilation failure.

package com.renzhikeji.annotation.processor;

import java.lang.annotation.*;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface RetryDatasource {
    String value default "";
}

The annotation’s retention policy is set to RetentionPolicy.CLASS so it is retained in the compiled class files for processing.

To enforce the single‑use rule, a custom annotation processor is written. The processor logs its lifecycle methods, specifies the supported annotation type, and checks that the annotation is applied to at most one element, throwing an exception otherwise.

public class RetryDataSourceCheckProcessor extends AbstractProcessor {
    public RetryDataSourceCheckProcessor() {
        super();
        System.out.println("RetryDataSourceCheckProcessor()============================");
    }

    @Override
    public Set
getSupportedAnnotationTypes() {
        System.out.println("getSupportedAnnotationTypes()============================" + RetryDatasource.class.getCanonicalName());
        return Set.of(RetryDatasource.class.getCanonicalName());
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        System.out.println("getSupportedSourceVersion()============================" + SourceVersion.latestSupported());
        return SourceVersion.latestSupported();
    }

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        System.out.println("init()============================");
    }

    @Override
    public boolean process(Set
annotations, RoundEnvironment roundEnv) {
        System.out.println("==============process ==============" + annotations);
        for (TypeElement annotation : annotations) {
            Set
elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(annotation);
            System.out.println("" + annotation + elementsAnnotatedWith);
            if (elementsAnnotatedWith.size() > 1) {
                throw new IllegalArgumentException("注解" + annotation + "用在了多个类型上" + elementsAnnotatedWith);
            }
        }
        return true;
    }
}

The processor must have a public no‑argument constructor (required by ServiceLoader ) and override getSupportedAnnotationTypes and getSupportedSourceVersion to specify its target annotation and Java version.

To register the processor, a file named javax.annotation.processing.Processor is placed under META-INF/services containing the fully qualified processor class name:

com.renzhikeji.annotation.processor.RetryDataSourceCheckProcessor

When compiled with Maven, the processor causes a build error if the annotation is used on more than one class, as shown by the example error output.

In summary, Java annotations are useful not only at runtime via reflection but also at compile time for tasks such as rule validation and code generation, and custom annotation processors enable these capabilities.

JavareflectionMavenAnnotationsAnnotation Processorcompile-time
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

login 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.