Simple example to illustrate the use of android annotation processor.
This code will create an annotation named @Activity
which is meant to target activities. The processor will generate a Navigator
class with static
methods to start the annotated activities.
dependencies {
/*...*/
implementation project(':annotation')
implementation 'com.squareup:javapoet:1.9.0'
implementation 'com.google.auto.service:auto-service:1.0-rc3'
}
dependencies {
/*...*/
implementation project(':annotation')
annotationProcessor project(':processor')
}
@Target(ElementType.TYPE) // To target classes
@Retention(RetentionPolicy.SOURCE)
public @interface Activity {
}
@AutoService(Processor.class) // DON'T FORGET THIS
public class ActivityProcessor extends AbstractProcessor{
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
/* initialize variables */
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
/* code generation happens here (using JavaPoet) */
return false;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(Activity.class.getCanonicalName());
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}