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.

1
  • 1
    Can you not create a method prepareActivity( ... );? Commented Oct 29, 2014 at 12:55

2 Answers 2

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(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Annotations can generate additional code (i.e. new classes and other files). They must not modify the code in which they are contained. See 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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.