项目作者: OmarAflak

项目描述 :
Simple example to illustrate the use of android annotation and annotation processor.
高级语言: Java
项目地址: git://github.com/OmarAflak/Annotation-Processor-Sample.git
创建时间: 2017-08-17T14:37:21Z
项目社区:https://github.com/OmarAflak/Annotation-Processor-Sample

开源协议:

下载


Annotation Processor Example

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.

Creation Steps (Android Studio)

1) File > New > New Module… > Java Library -> Name it “annotation”

2) File > New > New Module… > Java Library -> Name it “processor”

3) In processor build.gradle :

  1. dependencies {
  2. /*...*/
  3. implementation project(':annotation')
  4. implementation 'com.squareup:javapoet:1.9.0'
  5. implementation 'com.google.auto.service:auto-service:1.0-rc3'
  6. }

4) In app build.gradle :

  1. dependencies {
  2. /*...*/
  3. implementation project(':annotation')
  4. annotationProcessor project(':processor')
  5. }

5) Create new file called Activity.java in annotation module :

  1. @Target(ElementType.TYPE) // To target classes
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Activity {
  4. }

6) Create new file called ActivityProcessor.java in processor module :

  1. @AutoService(Processor.class) // DON'T FORGET THIS
  2. public class ActivityProcessor extends AbstractProcessor{
  3. @Override
  4. public synchronized void init(ProcessingEnvironment processingEnvironment) {
  5. /* initialize variables */
  6. }
  7. @Override
  8. public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
  9. /* code generation happens here (using JavaPoet) */
  10. return false;
  11. }
  12. @Override
  13. public Set<String> getSupportedAnnotationTypes() {
  14. return Collections.singleton(Activity.class.getCanonicalName());
  15. }
  16. @Override
  17. public SourceVersion getSupportedSourceVersion() {
  18. return SourceVersion.latestSupported();
  19. }
  20. }

7) Annotate any class and Rebuild your project to generate the code

Sample