├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── zyao89 │ │ └── demoabstractprocessor │ │ └── MainActivity.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── capture └── gif01.gif ├── compiler ├── .gitignore ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── zyao89 │ ├── MyProcessor.java │ └── ZyaoAnnotation.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | app/libs/ 10 | app/src/main/res/drawable/ 11 | compiler/libs/ 12 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | Abstraction issuesJava 39 | 40 | 41 | Android 42 | 43 | 44 | Android > Lint > Accessibility 45 | 46 | 47 | Android > Lint > Correctness 48 | 49 | 50 | Android > Lint > Correctness > Messages 51 | 52 | 53 | Android > Lint > Internationalization 54 | 55 | 56 | Android > Lint > Internationalization > Bidirectional Text 57 | 58 | 59 | Android > Lint > Performance 60 | 61 | 62 | Android > Lint > Security 63 | 64 | 65 | Android > Lint > Usability 66 | 67 | 68 | Android > Lint > Usability > Icons 69 | 70 | 71 | Android > Lint > Usability > Typography 72 | 73 | 74 | C/C++ 75 | 76 | 77 | Class metricsJava 78 | 79 | 80 | Class structureJava 81 | 82 | 83 | Cloning issuesJava 84 | 85 | 86 | Code style issuesJava 87 | 88 | 89 | Control FlowGroovy 90 | 91 | 92 | Control flow issuesJava 93 | 94 | 95 | CorrectnessLintAndroid 96 | 97 | 98 | Data flow analysisC/C++ 99 | 100 | 101 | Data flow issuesJava 102 | 103 | 104 | Declaration orderC/C++ 105 | 106 | 107 | Declaration redundancyJava 108 | 109 | 110 | Dependency issuesJava 111 | 112 | 113 | Encapsulation issuesJava 114 | 115 | 116 | Error handlingGroovy 117 | 118 | 119 | Error handlingJava 120 | 121 | 122 | Finalization issuesJava 123 | 124 | 125 | FunctionsC/C++ 126 | 127 | 128 | GPath inspectionsGroovy 129 | 130 | 131 | General 132 | 133 | 134 | GeneralC/C++ 135 | 136 | 137 | Google Cloud Endpoints 138 | 139 | 140 | Groovy 141 | 142 | 143 | ImportsJava 144 | 145 | 146 | Inheritance issuesJava 147 | 148 | 149 | Initialization issuesJava 150 | 151 | 152 | Internationalization issues 153 | 154 | 155 | Internationalization issuesJava 156 | 157 | 158 | J2ME issuesJava 159 | 160 | 161 | JSON 162 | 163 | 164 | JUnit issuesJava 165 | 166 | 167 | Java 168 | 169 | 170 | Java language level migration aidsJava 171 | 172 | 173 | Javadoc issuesJava 174 | 175 | 176 | Language Injection 177 | 178 | 179 | LintAndroid 180 | 181 | 182 | Logging issuesJava 183 | 184 | 185 | Manifest 186 | 187 | 188 | Memory issuesJava 189 | 190 | 191 | Method MetricsGroovy 192 | 193 | 194 | Method metricsJava 195 | 196 | 197 | Modularization issuesJava 198 | 199 | 200 | Naming ConventionsGroovy 201 | 202 | 203 | Naming conventionsJava 204 | 205 | 206 | Numeric issuesJava 207 | 208 | 209 | Pattern Validation 210 | 211 | 212 | Performance issuesJava 213 | 214 | 215 | Portability issuesJava 216 | 217 | 218 | Potentially confusing code constructsGroovy 219 | 220 | 221 | Probable bugsJava 222 | 223 | 224 | Properties Files 225 | 226 | 227 | Properties FilesJava 228 | 229 | 230 | Security issuesJava 231 | 232 | 233 | Serialization issuesJava 234 | 235 | 236 | Spelling 237 | 238 | 239 | TestNGJava 240 | 241 | 242 | Threading issuesGroovy 243 | 244 | 245 | Threading issuesJava 246 | 247 | 248 | Type checksC/C++ 249 | 250 | 251 | Unused codeC/C++ 252 | 253 | 254 | Validity issuesGroovy 255 | 256 | 257 | Visibility issuesJava 258 | 259 | 260 | XML 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 282 | 283 | 284 | 285 | 286 | 287 | 292 | 293 | 294 | 295 | 296 | 297 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AbstractProcessor Test Demo 2 | 3 | `作者:Zyao89;转载请保留此行,谢谢;` 4 | 5 | --- 6 | 7 | Java中的注解(Annotation)是一个很神奇的东西,特别现在有很多Android库都是使用注解的方式来实现的。 8 | 我们并不讨论那些在运行时(Runtime)通过反射机制运行处理的注解,而是讨论在编译时(Compile time)处理的注解。下面便入手学习下Java注解处理器。 9 | 10 | ### 基本概念 11 | **注解处理器**是一个在javac中的,用来编译时扫描和处理的注解的工具。你可以为特定的注解,注册你自己的注解处理器。 12 | 注解处理器可以生成Java代码,这些生成的Java代码会组成 `.java` 文件,但不能修改已经存在的Java类(即不能向已有的类中添加方法)。而这些生成的Java文件,会同时与其他普通的手写Java源代码一起被javac编译。 13 | 14 | 15 | ### 抽象处理器 AbstractProcessor 16 | > import javax.annotation.processing.AbstractProcessor; 17 | 18 | 我们每一个注解处理器都要继承于AbstractProcessor,如下所示: 19 | 20 | ```java 21 | public class MyProcessor extends AbstractProcessor 22 | { 23 | @Override 24 | public synchronized void init(ProcessingEnvironment processingEnvironment) 25 | { 26 | super.init(processingEnvironment); 27 | } 28 | 29 | @Override 30 | public boolean process(Set set, RoundEnvironment roundEnvironment) 31 | { 32 | return false; 33 | } 34 | 35 | @Override 36 | public Set getSupportedAnnotationTypes() 37 | { 38 | return super.getSupportedAnnotationTypes(); 39 | } 40 | 41 | @Override 42 | public SourceVersion getSupportedSourceVersion() 43 | { 44 | return super.getSupportedSourceVersion(); 45 | } 46 | } 47 | ``` 48 | 49 | * `init(ProcessingEnvironment processingEnvironment)`: 每一个注解处理器类都必须有一个空的构造函数。然而,这里有一个特殊的init()方法,它会被注解处理工具调用,并输入ProcessingEnviroment参数。ProcessingEnviroment提供很多有用的**工具类Elements,Types和Filer**。后面我们将看到详细的内容。 50 | * `process(Set set, RoundEnvironment roundEnvironment)`: 这相当于每个处理器的主函数main()。你在这里写你的扫描、评估和处理注解的代码,以及生成Java文件。输入参数RoundEnviroment,可以让你查询出包含特定注解的被注解元素。后面我们将看到详细的内容。 51 | * `getSupportedAnnotationTypes()`: 这里你必须指定,这个注解处理器是注册给哪个注解的。注意,它的返回值是一个字符串的集合,包含本处理器想要处理的注解类型的合法全称。换句话说,你在这里定义你的注解处理器注册到哪些注解上。 52 | * `getSupportedSourceVersion()`: 用来指定你使用的Java版本。通常这里返回SourceVersion.latestSupported()。然而,如果你有足够的理由只支持Java 7的话,你也可以返回SourceVersion.RELEASE_7。我推荐你使用前者。 53 | 54 | 在Java 7以后,你也可以使用注解来代替getSupportedAnnotationTypes()和getSupportedSourceVersion(),像这样: 55 | 56 | ```java 57 | @SupportedSourceVersion(SourceVersion.RELEASE_7) 58 | @SupportedAnnotationTypes({ 59 | "com.zyao89.ZyaoAnnotation" 60 | }) 61 | public class MyProcessor extends AbstractProcessor 62 | { 63 | @Override 64 | public synchronized void init(ProcessingEnvironment processingEnvironment) 65 | { 66 | super.init(processingEnvironment); 67 | } 68 | 69 | @Override 70 | public boolean process(Set set, RoundEnvironment roundEnvironment) 71 | { 72 | return false; 73 | } 74 | } 75 | ``` 76 | 77 | ### 简单实践 78 | 79 | 1. 首先我们来创建一个 `@ZyaoAnnotation` 注解,后面我们将用这个注解来自动生成一个java文件。 80 | 81 | 我们先来看下 `@ ZyaoAnnotation ` 注解: 82 | ```java 83 | @Target({ElementType.TYPE}) 84 | @Retention(RetentionPolicy.CLASS) 85 | public @interface ZyaoAnnotation 86 | { 87 | String name() default "undefined"; 88 | 89 | String text() default ""; 90 | } 91 | ``` 92 | 93 | 这时候我们可以在需要注解的类上增加我们的注解了,如: 94 | ```java 95 | @ZyaoAnnotation( 96 | name = "Zyao", 97 | text = "Hello !!! Welcome " 98 | ) 99 | public class MainActivity extends AppCompatActivity 100 | { 101 | 102 | @Override 103 | protected void onCreate(Bundle savedInstanceState) 104 | { 105 | super.onCreate(savedInstanceState); 106 | setContentView(R.layout.activity_main); 107 | } 108 | } 109 | ``` 110 | 111 | 这时,注解都注解完了,那我们该怎么运行呢?请看下面。 112 | 113 | ### 处理器 114 | 这里我们通过代码加注释的方式,来一步步构建我们想要的处理器。代码如下: 115 | ```java 116 | @AutoService(Processor.class) 117 | public class MyProcessor extends AbstractProcessor 118 | { 119 | private Types mTypeUtils; 120 | private Elements mElementUtils; 121 | private Filer mFiler; 122 | private Messager mMessager; 123 | 124 | @Override 125 | public synchronized void init(ProcessingEnvironment processingEnvironment) 126 | { 127 | super.init(processingEnvironment); 128 | 129 | //初始化我们需要的基础工具 130 | mTypeUtils = processingEnv.getTypeUtils(); 131 | mElementUtils = processingEnv.getElementUtils(); 132 | mFiler = processingEnv.getFiler(); 133 | mMessager = processingEnv.getMessager(); 134 | } 135 | 136 | @Override 137 | public SourceVersion getSupportedSourceVersion() 138 | { 139 | //支持的java版本 140 | return SourceVersion.latestSupported(); 141 | } 142 | 143 | @Override 144 | public Set getSupportedAnnotationTypes() 145 | { 146 | //支持的注解 147 | Set annotations = new LinkedHashSet<>(); 148 | annotations.add(ZyaoAnnotation.class.getCanonicalName()); 149 | return annotations; 150 | } 151 | 152 | @Override 153 | public boolean process(Set set, RoundEnvironment roundEnvironment) 154 | { 155 | //这里开始处理我们的注解解析了,以及生成Java文件 156 | return false; 157 | } 158 | } 159 | ``` 160 | 161 | 大家看到第一行`@AutoService(Processor.class)` 这个有木有?这是一个注解处理器,是Google开发的,用来生成META-INF/services/javax.annotation.processing.Processor文件的。 162 | 163 | Gradle引入方式: 164 | > compile 'com.google.auto.service:auto-service:1.0-rc2' 165 | 166 | 在`getSupportedAnnotationTypes()`中,我们指定本处理器将处理 `@ZyaoAnnotation` 注解。 167 | 168 | 169 | ### 基础工具解析 170 | 171 | 在init()中我们获得如下引用: 172 | 173 | - **Elements**:一个用来处理Element的工具类,源代码的每一个部分都是一个特定类型的Element,例如: 174 | 175 | ```java 176 | package com.example; // PackageElement 177 | 178 | public class Foo { // TypeElement 179 | 180 | private int a; // VariableElement 181 | private Foo other; // VariableElement 182 | 183 | public Foo () {} // ExecuteableElement 184 | 185 | public void setA ( // ExecuteableElement 186 | int newA // TypeElement 187 | ) {} 188 | } 189 | ``` 190 | 举例来说,假如你有一个代表public class Foo类的TypeElement元素,你可以遍历它的孩子,如下: 191 | ```java 192 | TypeElement fooClass = ... ; 193 | for (Element e : fooClass.getEnclosedElements()){ // iterate over children 194 | Element parent = e.getEnclosingElement(); // parent == fooClass 195 | } 196 | ``` 197 | TypeElement并不包含类本身的信息。你可以从TypeElement中获取类的名字,但是你获取不到类的信息,例如它的父类。这种信息需要通过TypeMirror获取。你可以通过调用elements.asType()获取元素的TypeMirror。 198 | 199 | 200 | - **Types**:一个用来处理TypeMirror的工具类;(后面会使用到,在进行讲解) 201 | 202 | - **Filer**:正如这个名字所示,使用Filer你可以创建文件。 203 | 204 | 205 | ### 搜索@ZyaoAnnotation注解 206 | ``` 207 | @Override 208 | public boolean process(Set set, RoundEnvironment roundEnvironment) 209 | {//这里开始处理我们的注解解析了,以及生成Java文件 210 | 211 | // 遍历所有被注解了@Factory的元素 212 | for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(ZyaoAnnotation.class)) { 213 | ... 214 | } 215 | 216 | 217 | return false; 218 | } 219 | ``` 220 | 221 | `roundEnvironment.getElementsAnnotatedWith(ZyaoAnnotation.class)`返回所有被注解了@Factory的元素的列表。你可能已经注意到,我们并没有说“所有被注解了@Factory的类的列表”,因为它真的是返回Element的列表。请记住:Element可以是类、方法、变量等。所以,接下来,我们必须检查这些Element是否是一个类: 222 | 223 | ```java 224 | // 遍历所有被注解了@Factory的元素 225 | for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(ZyaoAnnotation.class)) { 226 | // 检查被注解为@Factory的元素是否是一个类 227 | if (annotatedElement.getKind() != ElementKind.CLASS) { 228 | error(annotatedElement, "Only classes can be annotated with @%s", 229 | ZyaoAnnotation.class.getSimpleName()); 230 | return true; // 退出处理 231 | } 232 | 233 | //解析,并生成代码 234 | analysisAnnotated(annotatedElement); 235 | } 236 | ``` 237 | 238 | 这里就配合了`TypeMirror`使用`EmentKind`或者`TypeKind`进行元素类型判断。 239 | 240 | `error()`日志和错误信息打印: 241 | ```java 242 | private void error(Element e, String msg, Object... args) { 243 | mMessager.printMessage( 244 | Diagnostic.Kind.ERROR, 245 | String.format(msg, args), 246 | e); 247 | } 248 | ``` 249 | 250 | 除了`Diagnostic.Kind.ERROR`日志等级,还有其它,如: 251 | ```java 252 | public static enum Kind { 253 | ERROR, 254 | WARNING, 255 | MANDATORY_WARNING, 256 | NOTE, 257 | OTHER; 258 | 259 | private Kind() { 260 | } 261 | } 262 | ``` 263 | 264 | ### 代码生成 265 | 编写解析和生成的代码格式: 266 | ```java 267 | private static final String SUFFIX = "$$ZYAO"; 268 | 269 | private void analysisAnnotated(Element classElement) 270 | { 271 | ZyaoAnnotation annotation = classElement.getAnnotation(ZyaoAnnotation.class); 272 | String name = annotation.name(); 273 | String text = annotation.text(); 274 | 275 | // TypeElement superClassName = mElementUtils.getTypeElement(name); 276 | String newClassName = name + SUFFIX; 277 | 278 | StringBuilder builder = new StringBuilder() 279 | .append("package com.zyao89.demoprocessor.auto;\n\n") 280 | .append("public class ") 281 | .append(newClassName) 282 | .append(" {\n\n") // open class 283 | .append("\tpublic String getMessage() {\n") // open method 284 | .append("\t\treturn \""); 285 | 286 | // this is appending to the return statement 287 | builder.append(text).append(name).append(" !\\n"); 288 | 289 | 290 | builder.append("\";\n") // end return 291 | .append("\t}\n") // close method 292 | .append("}\n"); // close class 293 | 294 | 295 | try { // write the file 296 | JavaFileObject source = mFiler.createSourceFile("com.zyao89.demoprocessor.auto."+newClassName); 297 | Writer writer = source.openWriter(); 298 | writer.write(builder.toString()); 299 | writer.flush(); 300 | writer.close(); 301 | } catch (IOException e) { 302 | // Note: calling e.printStackTrace() will print IO errors 303 | // that occur from the file already existing after its first run, this is normal 304 | } 305 | 306 | info(">>> analysisAnnotated is finish... <<<"); 307 | } 308 | ``` 309 | 以上的连接字符串工作,可以使用`JavaPoet`开源库进行编写,提升效率。 310 | 311 | ```gradle 312 | compile 'com.squareup:javapoet:1.7.0' 313 | ``` 314 | 315 | 最后build一下工程,生成最终的java文件 `Zyao$$ZYAO.java` 316 | 317 | > 生成的文件路径: 318 | /DemoAbstractProcessor/app/build/generated/source/apt/debug/com/zyao89/demoprocessor/auto/Zyao$$ZYAO.java 319 | 320 | 文件内容: 321 | 322 | ```java 323 | package com.zyao89.demoprocessor.auto; 324 | 325 | public class Zyao$$ZYAO { 326 | 327 | public String getMessage() { 328 | return "Hello !!! Welcome Zyao !\n"; 329 | } 330 | } 331 | ``` 332 | 333 | ### 运行 334 | 335 | ```java 336 | @ZyaoAnnotation( 337 | name = "Zyao", 338 | text = "Hello !!! Welcome " 339 | ) 340 | public class MainActivity extends AppCompatActivity 341 | { 342 | 343 | @Override 344 | protected void onCreate(Bundle savedInstanceState) 345 | { 346 | super.onCreate(savedInstanceState); 347 | setContentView(R.layout.activity_main); 348 | 349 | } 350 | 351 | public void changeText(View view) { 352 | Zyao$$ZYAO zyao$$ZYAO = new Zyao$$ZYAO(); 353 | String message = zyao$$ZYAO.getMessage(); 354 | ((TextView)view).setText(message); 355 | } 356 | } 357 | ``` 358 | 359 | 最终运行我们的程序,点击文本,可得到我们的`getMessage`内容。 360 | 361 | 362 | ### 演示图 363 | ![演示图](./capture/gif01.gif) 364 | 365 | --- 366 | 367 | `作者:Zyao89;转载请保留此行,谢谢;` 368 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | defaultConfig { 7 | applicationId "com.zyao89.demoabstractprocessor" 8 | minSdkVersion 15 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | compile 'com.android.support:appcompat-v7:25.1.0' 25 | annotationProcessor project(path: ':compiler') 26 | compile project(path: ':compiler') 27 | } 28 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/zyao89/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/java/com/zyao89/demoabstractprocessor/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.zyao89.demoabstractprocessor; 2 | 3 | import android.support.v7.app.AppCompatActivity; 4 | import android.os.Bundle; 5 | import android.view.View; 6 | import android.widget.TextView; 7 | 8 | import com.zyao89.ZyaoAnnotation; 9 | import com.zyao89.demoprocessor.auto.Zyao$$ZYAO; 10 | 11 | @ZyaoAnnotation( 12 | name = "Zyao", 13 | text = "Hello !!! Welcome " 14 | ) 15 | public class MainActivity extends AppCompatActivity 16 | { 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) 20 | { 21 | super.onCreate(savedInstanceState); 22 | setContentView(R.layout.activity_main); 23 | 24 | } 25 | 26 | public void changeText(View view) { 27 | Zyao$$ZYAO zyao$$ZYAO = new Zyao$$ZYAO(); 28 | String message = zyao$$ZYAO.getMessage(); 29 | ((TextView)view).setText(message); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | DemoAbstractProcessor 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.3' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /capture/gif01.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/capture/gif01.gif -------------------------------------------------------------------------------- /compiler/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /compiler/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | dependencies { 4 | compile fileTree(dir: 'libs', include: ['*.jar']) 5 | compile 'com.google.auto.service:auto-service:1.0-rc2' 6 | } 7 | 8 | sourceCompatibility = "1.7" 9 | targetCompatibility = "1.7" 10 | -------------------------------------------------------------------------------- /compiler/src/main/java/com/zyao89/MyProcessor.java: -------------------------------------------------------------------------------- 1 | package com.zyao89; 2 | 3 | import com.google.auto.service.AutoService; 4 | 5 | import java.io.IOException; 6 | import java.io.Writer; 7 | import java.util.LinkedHashSet; 8 | import java.util.Set; 9 | 10 | import javax.annotation.processing.AbstractProcessor; 11 | import javax.annotation.processing.Filer; 12 | import javax.annotation.processing.Messager; 13 | import javax.annotation.processing.ProcessingEnvironment; 14 | import javax.annotation.processing.Processor; 15 | import javax.annotation.processing.RoundEnvironment; 16 | import javax.lang.model.SourceVersion; 17 | import javax.lang.model.element.Element; 18 | import javax.lang.model.element.ElementKind; 19 | import javax.lang.model.element.TypeElement; 20 | import javax.lang.model.util.Elements; 21 | import javax.lang.model.util.Types; 22 | import javax.tools.Diagnostic; 23 | import javax.tools.JavaFileObject; 24 | 25 | @AutoService(Processor.class) 26 | public class MyProcessor extends AbstractProcessor 27 | { 28 | private Types mTypeUtils; 29 | private Elements mElementUtils; 30 | private Filer mFiler; 31 | private Messager mMessager; 32 | 33 | @Override 34 | public synchronized void init(ProcessingEnvironment processingEnvironment) 35 | { 36 | super.init(processingEnvironment); 37 | 38 | //初始化我们需要的基础工具 39 | mTypeUtils = processingEnv.getTypeUtils(); 40 | mElementUtils = processingEnv.getElementUtils(); 41 | mFiler = processingEnv.getFiler(); 42 | mMessager = processingEnv.getMessager(); 43 | } 44 | 45 | @Override 46 | public SourceVersion getSupportedSourceVersion() 47 | { 48 | //支持的java版本 49 | return SourceVersion.RELEASE_7; 50 | } 51 | 52 | @Override 53 | public Set getSupportedAnnotationTypes() 54 | { 55 | //支持的注解 56 | Set annotations = new LinkedHashSet<>(); 57 | annotations.add(ZyaoAnnotation.class.getCanonicalName()); 58 | return annotations; 59 | } 60 | 61 | @Override 62 | public boolean process(Set set, RoundEnvironment roundEnvironment) 63 | {//这里开始处理我们的注解解析了,以及生成Java文件 64 | if (set == null || set.isEmpty()) 65 | { 66 | info(">>> set is null... <<<"); 67 | return true; 68 | } 69 | 70 | info(">>> Found field, start... <<<"); 71 | 72 | Set elements = roundEnvironment.getElementsAnnotatedWith(ZyaoAnnotation.class); 73 | 74 | if (elements == null || elements.isEmpty()) 75 | { 76 | info(">>> elements is null... <<<"); 77 | return true; 78 | } 79 | 80 | // 遍历所有被注解了@Factory的元素 81 | for (Element annotatedElement : elements) { 82 | 83 | // 检查被注解为@Factory的元素是否是一个类 84 | if (annotatedElement.getKind() != ElementKind.CLASS) { 85 | error(annotatedElement, "Only classes can be annotated with @%s", 86 | ZyaoAnnotation.class.getSimpleName()); 87 | return true; // 退出处理 88 | } 89 | 90 | analysisAnnotated(annotatedElement); 91 | } 92 | 93 | return true; 94 | } 95 | 96 | private static final String SUFFIX = "$$ZYAO"; 97 | 98 | private void analysisAnnotated(Element classElement) 99 | { 100 | ZyaoAnnotation annotation = classElement.getAnnotation(ZyaoAnnotation.class); 101 | String name = annotation.name(); 102 | String text = annotation.text(); 103 | 104 | // TypeElement superClassName = mElementUtils.getTypeElement(name); 105 | String newClassName = name + SUFFIX; 106 | 107 | StringBuilder builder = new StringBuilder() 108 | .append("package com.zyao89.demoprocessor.auto;\n\n") 109 | .append("public class ") 110 | .append(newClassName) 111 | .append(" {\n\n") // open class 112 | .append("\tpublic String getMessage() {\n") // open method 113 | .append("\t\treturn \""); 114 | 115 | // this is appending to the return statement 116 | builder.append(text).append(name).append(" !\\n"); 117 | 118 | 119 | builder.append("\";\n") // end return 120 | .append("\t}\n") // close method 121 | .append("}\n"); // close class 122 | 123 | 124 | try { // write the file 125 | JavaFileObject source = mFiler.createSourceFile("com.zyao89.demoprocessor.auto."+newClassName); 126 | Writer writer = source.openWriter(); 127 | writer.write(builder.toString()); 128 | writer.flush(); 129 | writer.close(); 130 | } catch (IOException e) { 131 | // Note: calling e.printStackTrace() will print IO errors 132 | // that occur from the file already existing after its first run, this is normal 133 | } 134 | 135 | info(">>> analysisAnnotated is finish... <<<"); 136 | } 137 | 138 | private void error(Element e, String msg, Object... args) { 139 | mMessager.printMessage( 140 | Diagnostic.Kind.ERROR, 141 | String.format(msg, args), 142 | e); 143 | } 144 | 145 | private void info(String msg, Object... args) { 146 | mMessager.printMessage( 147 | Diagnostic.Kind.NOTE, 148 | String.format(msg, args)); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /compiler/src/main/java/com/zyao89/ZyaoAnnotation.java: -------------------------------------------------------------------------------- 1 | package com.zyao89; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by zyao89 on 2017/2/26. 10 | * Contact me at 305161066@qq.com or zyao89@gmail.com 11 | * For more projects: https://github.com/zyao89 12 | */ 13 | @Target({ElementType.TYPE}) 14 | @Retention(RetentionPolicy.CLASS) 15 | public @interface ZyaoAnnotation 16 | { 17 | String name() default "undefined"; 18 | 19 | String text() default ""; 20 | } 21 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zyao89/DemoAbstractProcessor/870ae385345d8769bf95c7c6799a613587f360db/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':compiler' 2 | --------------------------------------------------------------------------------