5

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.

MainstreamDeveloper00
  • 8,436
  • 15
  • 56
  • 102

2 Answers2

4

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

Community
  • 1
  • 1
Icewind
  • 873
  • 4
  • 16
4

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();
}
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Thanks. This helps!But can you please explain why Annotations aren't meant to change code? I thought they was design for code generating.And libraries like `Google Guice`, `Spring` or `Dagger` use this heavily. Or I misunderstood something? – MainstreamDeveloper00 Oct 30 '14 at 13:11
  • Annotations can generate additional code (i.e. new classes and other files). They must not modify the code in which they are contained. See http://docs.oracle.com/javase/tutorial/java/annotations/ The libraries you mention use the annotations to run additional checks on the code (no modification), find classes and methods on the classpath, etc. None of them actually modify the byte code of the class which contain the annotation. – Aaron Digulla Oct 30 '14 at 13:17