views:

431

answers:

2

Is it possible to create a preprocessor like functionality that is available in C and provided by Antenna. Can we use the APT tool to achieve this functionality? Are there any articles or links on similar topics?

+2  A: 

Annotations are not meant as a tool to transform code; they just add metadata to code. You can't use annotations for conditional compilation, for example.

As Sun's tutorial on annotations says:

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

Wikipedia says:

When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed, but processors cannot modify the annotated code itself.

So an annotation processor plug-in is not going to be able to give you all of the functionality that the C preprocessor has.

Jesper
+2  A: 

You can perform compile-time tasks using the annotation processing framework. It's not as powerful as a preprocessor, since you can't do things like:

@RunOnlyOn(OS.Mac) public void someMethod() { ... }

Some good use cases for annotation processors are:

  • creating mapping files from annotated classes, e.g. create a hibernate mapping file;
  • creating indexes of classes which have certain annotation, e.g. create testng xml files from a source folder of test classes;
  • enforce compile-time constraints not usually available, e.g. having a no-arg constructor.

Please note that as of Java 6 APT is no longer needed, since all properly declared annotation processors take part in the compilation.

Robert Munteanu
Actually you can if you make your own annotation checking classloader and implement the annotation yourself; however it's not worth the time most of the times.
Esko
@Esko : that sounds distressingly interesting :-) Do you have a link for a proof-of-concept?
Robert Munteanu
Erm, I guess I could make one (haven't really written ClassLoaders myself) but it would take some time. Damn, now you got me thinking of actually doing it :) I'll report back eventually if I come up with something useful, just don't hold your breath :)
Esko