Java preprocessor

If you have developed applications using C, you are probably aware of preprocessor. If you have ever worked with JNI code, you recall preprocessor’s directives for sure. You can find lots of them inside JNI based code generated through javah or javac -h.

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class recipeNo001_HelloWorld */

#ifndef _Included_recipeNo001_HelloWorld
#define _Included_recipeNo001_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     recipeNo001_HelloWorld
 * Method:    displayMessage
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_recipeNo001_HelloWorld_displayMessage
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

These directives let you change the code before it even gets compiled. This is quite powerful feature, it lets you adapt the code to environment you work with. It’s very useful while working with software, where various, incompatible, APIs must be supported – due to various factors.

You can also maintain different behavior in release and debug mode. You can simply control what gets into final version of the product.

It’s fairly easy to achieve similar (not exactly the same), behavior in Java. Java, by design, doesn’t provide preprocessor’s annotations. To get it working, you have to use some external preprocessing engine. Fortunately, there is one: <#FreeMarker>.

You can easily adapt it to get your Java source code preprocessed before it is being passed to Java compiler. Take a look below, inside jpp repo, to get the glimpse of what’s possible.

Leave a comment

Your comment