Writing your own Annotation Processors in Android

Hitanshu Dhawan
Sep 17, 2018 · 6 min read
Image for post
Image for post

What are Annotations ?

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface BindView {
int value();
}

Why Annotation Processors ?

1. Compile time

2. No Reflection

3. Generate boilerplate code*

How does Annotation Processing work ?

Image for post
Image for post
image courtesy: Jorge Castillo

How to register a Processor ?

package foo.bar;import javax.annotation.processing.Processor;@AutoService(Processor.class)
final class MyProcessor implements Processor {
// …
}

How to create a Processor ?

public class Processor extends AbstractProcessor {    @Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
// initialize helper/utility classes...
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
// do processing...
return true;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return new HashSet<String>() {{
add(BindView.class.getCanonicalName());
add(OnClick.class.getCanonicalName());
}};
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}

Demo #1 : Singleton

@Singleton
public class MySingleton {
private MySingleton() {}
public static MySingleton getInstance() {
return new MySingleton();
}
}

Demo #2 : KSingleton

Important Classes/Objects

How to generate .java files ?

package com.example.helloworld;public final class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, JavaPoet!");
}
}
MethodSpec main = MethodSpec.methodBuilder("main")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(void.class)
.addParameter(String[].class, "args")
.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
javaFile.writeTo(System.out);

Demo #3 : ButterKnife

public class MainActivity extends AppCompatActivity {    private int numberOfTimesTextViewClicked = 0;    @BindView(R.id.text_view)
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.text_view)
void onTextViewClicked(View view) {
textView.setText(String.valueOf(++numberOfTimesTextViewClicked));
}
}
public class MainActivityBinder {
public MainActivityBinder(MainActivity activity) {
bindViews(activity);
bindOnClicks(activity);
}
private void bindViews(MainActivity activity) {
activity.textView = (TextView) activity.findViewById(2131165314);
}
private void bindOnClicks(final MainActivity activity) {
activity.findViewById(2131165314).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
activity.onTextViewClicked(view);
}
});
}
}

Conclusion


AndroIDIOTS

An android developer publication to stay updated with whats…

Hitanshu Dhawan

Written by

Software Engineer @UrbanClap | Google Certified Android Developer

AndroIDIOTS

An android developer publication to stay updated with whats new in android, best practices and how to become a better android developer

Hitanshu Dhawan

Written by

Software Engineer @UrbanClap | Google Certified Android Developer

AndroIDIOTS

An android developer publication to stay updated with whats new in android, best practices and how to become a better android developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store