1

I have JAVA library that I am working on and I am using Ant build system, I am trying to generate a .jar file from and using in another application, what I am trying to do is to enable some specific ENV variables only in Debug build and have them disabled in production/release, and I was wondering how can I achieve that? In my build.xml I have a property called "debug", which is boolean.

In C/C++ You have the NDEBUG macros where you can define what you will exclude/include in debug mode, is there something similar in JAVA?

I have tried to read Ant documentation, I see that they use properties but the documentation doesn't state exactly how you can pass those properties into the source code, In fact, I tried to do that but with no success.

pureofpure
  • 1,060
  • 2
  • 12
  • 31
  • Java doesn't feature conditional compilation like that. You could either detect if your code is running from a jar file (i.e. treat a non-packaged build as a debug build) or just make the behavior dependent on some environment variable (then it would still be accessible in the final build, but only if explicitly enabled) or other such approach. In *theory* you could even have separate versions of some classes to compile in some special mode, but that's a terrible idea, because now you have two code bases: one which is tested during development and the other one that you ship. – Joachim Sauer Oct 05 '20 at 16:02

1 Answers1

0

As mentioned by @Joachim Sauer above, Java does not feature conditional compilation. You can argue either way for this being a good feature, but it's not available. What can you do, then?

One method you can use is to write information into the jar's manifest. For example, you could include the build version and your debug flag like so:

<jar destfile="my.jar" basedir="build/classes">
    <manifest>
        <attribute name="Package-Title" value="My Package Title" />
        <attribute name="Package-Version" value="${build.current.version}" />
        <attribute name="Debug" value="${debug}" />
    </manifest>
</jar>

Then, in your code, you would attempt to read your own jar's manifest: Reading my own Jar's Manifest

Another simpler option might be to include a properties file in your jar, and just read that. You can use the ant task 'echo' to write out a properties file before the jar task:

<echo file="build/classes/my.properties" encoding="ISO-8859-1"  append="false">
    Package-Title: ${package-title}
    Package-Version: ${build.current.version}
    com.example.app.debug=${debug}
</echo>

Then, you can just open "my.properties" in the code as a resource, and use that.

Jamie
  • 1,888
  • 1
  • 18
  • 21