How to provide preprocessor directives in Java

49.1k Views Asked by At

CHow can I correctly provide the following functionally from C# in Java?

[C#]

#define PRODUCTION //Change from sandbox to production to switch between both systems.

#if SANDBOX
    using NetSuite.com.netsuite.sandbox.webservices;
#endif

#if PRODUCTION
    using NetSuite.com.netsuite.webservices;
#endif
5

There are 5 best solutions below

3
On BEST ANSWER

Java doesn't have a preprocessor - so the simple answer is that you can't.

This sort of thing is normally handled in Java using Dependency Injection - which is both more powerful and more flexible.

http://www.vogella.com/articles/DependencyInjection/article.html

3
On

Use Dependency Injection/Inversion of Control. Depending on your actual needs, you might be able to get away with something as simple as property file/environment variables to control things.

You might be able to use static defines around some types of initialization/code.

1
On

Java doesn't have a preprocessor, yet that doesn't mean that you can't run Java code through cpp - though it would not be supported by any tools, AFAIK.

0
On

You can use something based on <#FreeMarker>.

enter image description here

source: https://github.com/mkowsiak/jpp

However, this solution will require pre-compilation step, if you want to change the code. On the other hand, you can still create code that works without pre-processing steps - sort of "default" compilation.

0
On

I'm using java-comment-preprocessor. It is very easy and convenient and provides also integration for Maven, Ant and Gradle. It is using Java comments and a preprocessor is used generating the actual code based on the preprocessor flags, e.g.:

//#if simulator
private final static int FOO = 2;
//#else
private final static int FOO = 1;
//#endif

Maven integration:

<plugin>
                <groupId>com.igormaznitsa</groupId>
                <artifactId>jcp</artifactId>
                <version>7.0.5</version>
                <executions>
                    <execution>
                        <id>preprocessSources</id>
                        <phase>process-sources</phase>
                        <goals>
                            <goal>preprocess</goal>
                        </goals>
                        <configuration>
                            <vars>
                                <simulator>${simulator}</simulator>
                            </vars>
                        </configuration>
                    </execution>
                </executions>
            </plugin>