javaconfiguration

Java environment-dependent compilation


I've seen answers on here that you can use final static const variables in Java to prevent sections of code from getting compiled. My concern with that approach is that I'm forgetful. :-( I'm likely to forget to set the variable back to false before I check the code in, and which could negatively impact the project.

In C/C++, you can specify environment macros that can be used to control the compilation of code. For example:

#if defined(_PROFILE)
Time startTime;
#endif

... run some code ...

#if defined(_PROFILE)
Time endTime;
std::cout << "Code took " << endTime - startTime << " seconds\n";
#endif

So the profiling test code would only get compiled if someone specifically defined the _PROFILE macro which could be passed as an option on the command line of the compiler and have no risk of getting checked in accidentally.

Is there any way to mimic this in Java?


Solution

  • You can use a runtime property. As Java is compiled dynamically it has much the same effect.

     static final boolean PROFILE = Boolean.getBoolean("VictimZero.PROFILE");
    
     long startTime;
     if (PROFILE)
        startTime = System.nanoTime();
    
     ... run some code ...
    
     if (PROFILE) {
        long enTime = System.nanoTime();
        System.out.printf("Code took %.3f seconds%n", (endTime - startTime)/1e9);
     }
    

    You can use the slightly hacky

     static final boolean VICTIM_ZERO = 
                             System.getProperty("user.name").equals("VictimZero");