Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Annotation processing: generate code, eliminate...

Annotation processing: generate code, eliminate boilerplate

Annotation processing is a tool built in javac for scanning and processing annotations at compile time. In this talk, we go through the steps of if how it works and how to create one for Android using Kotlin and java.

Rygel Louv

March 24, 2018
Tweet

More Decks by Rygel Louv

Other Decks in Programming

Transcript

  1. WHAT IS ANNOTATION PROCESSING ? Part of Java compiler Java

    5 Improved in Java 6 Scans annotations Process annotations At compile time
  2. WHAT ARE THE BENEFITS OF THAT ? Code generator written

    once Trustable Eliminate boilerplate code Improve productivity Don’t repeat yourself
  3. BUILD AP: WHICH COMPONENTS ? Annotation Processor APT: Annotation Processing

    Tool android-apt App code with annotated element For Android annotationProcessor kapt
  4. STEPS OF AP: HOW DOES IT WORK ? Build starts

    in javac Starts all annotation processors which are not executed Loop over annotated elements inside the processor Find annotated classes, methods, fields etc. Generated new classes with metadata of founded classes Create new files and write the generated string as class Compiler checks if all annotation processors are executed. If not start next ROUND
  5. BUILD OUR OWN AP: MODULES Create a new project: Android,

    Java, or Kotlin Create annotation module : Java/Kotlin Create processor module: Java/Kotlin
  6. BUILD OUR OWN AP: THE PROCESSOR Init(): gives tools (Messager

    and Filer) getSupportedAnnotationType(): returns only our custom annotations getSupportedSourceVersion(): Always return latest java version process(): This were the magic happen. Starts rounding and gives all annotated elements
  7. BUILD OUR OWN AP: THE PROCESSOR In the processor you

    loop over Elements in order to make calculations
  8. BUILD OUR OWN AP: TELL JAVAC ABOUT YOUR PROCESSOR Register

    the processor for it to be found by ServiceLoader Use AutoService
  9. BUILD OUR OWN AP: THE RULES Cannot modify existing files

    Runs in the compile time in its own jvm instance Dependencies are its own and do not impact the main project
  10. CODE GENERATION JavaPoet Kotlin Poet Kotlin annotation processing is a

    bit tricky Temporary solution: Generate .java file in kotlin