Annotation Processor Sample


Source link: https://github.com/mirrajabi/annotation-processor-sample

annotation-processor-sample

This is not a "Builder pattern" tutorial or something like that. It is about how we can make an annotation processor to avoid boilerplates and repeated codes.

What does this apt do?

Well lets take a look at a very simple type of bean with getters and builder setters:

public class TestClass {

  private long id;
  private String name;
  private int someField;
  private Activity activity;

public long getId() {

return id;
  
}

public TestClass setId(long id) {

this.id = id;

return this;
  
}

public String getName() {

return name;
  
}

public TestClass setName(String name) {

this.name = name;

return this;
  
}

public int getSomeField() {

return someField;
  
}

public TestClass setSomeField(int someField) {

this.someField = someField;

return this;
  
}

public Activity getActivity() {

return activity;
  
}

public TestClass setActivity(Activity activity) {

this.activity = activity;

return this;
  
}
 
}

And we instantiate this class like

TestClass testClass = new TestClass()
  ...
  .setSomeField(...)
  .setName(...)

So we have four fields and implemented 4+4 getter and setter methods. Now, what if we had 15 fields? we would have to make 15 getters and 15 setters. That's a total of 30! Of course today its very easy to use IDEs to make that boilerplate for us. but this is just an example of how much we use boilerplate codes. there are a whole lot of other examples for this topic. For example take a look at ButterKnife. This library took us out of the darkness. It made our world a better place.

with this apt(Annotation Processing Tool) all you have to do is to annotate your POJO with @Builder and make our fields non private

@Builder public class TestClass {

  long id;
  String name;
  int someField;
  Activity activity; 
}

@Builder does no magic. it just creates all the boilerplates we need and puts them inside another java class called %CLASS_NAME%Builder.java under app/build/generated/source/apt/debug/%PACKAGE_NAME%/ folder.

For example TestClassBuilder.java looks like this :

// This file is auto-generated and should not be edited. package ir.mirrajabi.aptsample;  import android.app.Activity; import java.lang.String;  public class TestClassBuilder {

private TestClass buildable;
 private TestClassBuilder() {

}

 public TestClassBuilder someField(int someField) {

  buildable.someField = someField;
  return this;

}

 public TestClassBuilder activity(Activity activity) {

  buildable.activity = activity;
  return this;

}

 public TestClassBuilder id(long id) {

  buildable.id = id;
  return this;

}

 public TestClassBuilder name(String name) {

  buildable.name = name;
  return this;

}

 public static TestClassBuilder having() {

  return new TestClassBuilder();

}

 TestClass get() {

  return this.buildable;

}
 
}

And we make and instance of our TestClass like this:

TestClass testClass = TestClassBuilder.having()

  .activity(this)

  .someField(5)

  .id(654)

  .name("Sample")

  .get();

But remember, we just annotated our class with @Builder and nothing else. the compiler did the rest for us.

I guess thats enough for a readme :))

Useful reads

Used libraries

Resources

Tool which allows to quickly try the demo project of any Android Library

Dexposed is a powerful yet non-invasive runtime AOP (Aspect-oriented Programming) framework for Android app development, based on the work of open-source Xposed framework project.

A method call logging based on dexposed.

A gallery used to host an array of images.

Android library to use Google Analytics through annotations.

The SimpleCropView is an image cropping library for Android. It simplify your code for cropping image and provides easily customizable UI.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes