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.
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.
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.
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 [...].
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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With