Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Java annotations to insert some boilerplate code as with C macro?

I want to use Java annotations to insert code (method invocations and so on). Let's say I have such code:

     ActionBar bar = getActionBar();
     assert bar != null;
     bar.setIcon(android.R.color.transparent);
     EventBus.getDefault().register(this);
     checkGPS();

This code appears in each my Activity class. And instead of writing it each time I want to have something like this : @PrepareActivity which will expand code. In C or C++ I can simply use #define PrepareActivity \ .... Can I write the same with Java annotations? And how to do this? Thanks.

like image 207
MainstreamDeveloper00 Avatar asked Oct 29 '14 12:10

MainstreamDeveloper00


People also ask

Is a Java annotation used to add data about code?

Annotations are used to provide supplemental information about a program. Annotations start with '@'. Annotations do not change the action of a compiled program. Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.

What can you do with Java annotations?

Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings. Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.

Which annotation is used for adding an object?

A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses. This form of annotation is called a type annotation [...].


2 Answers

Annotations aren't meant to change the code. There are special Java compilers (for example Projekt Lombok) which bend those rules.

But you don't need anything fancy. Just make the class implement an interface which contains getActionBar() and checkGPS() and then you can write a static helper method:

public static void prepare( IThing thing ) {
     ActionBar bar = thing.getActionBar();
     assert bar != null;
     bar.setIcon(android.R.color.transparent);
     EventBus.getDefault().register(this);
     thing.checkGPS();
}
like image 158
Aaron Digulla Avatar answered Oct 29 '22 01:10

Aaron Digulla


What I gather from answers to this this post, there seems to be no standard way of doing what you want. It might be possible using Aspect oriented programming, or maybe an answer in the linked post can help?

Project Lombok does something similar and they explain their trick here

like image 22
Icewind Avatar answered Oct 29 '22 01:10

Icewind