Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there any way to define a constant value to Java at compile time
    text
    copied!<p>When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code:</p> <p>C++:</p> <pre><code>#ifdef _BuildDateTime_ char* SomeClass::getBuildDateTime() { return _BuildDateTime_; } #else char* SomeClass::getBuildDateTime() { return "Undefined"; } #endif </code></pre> <p>Then on the compile I had a '-D_BuildDateTime_=<code>Date</code>' in the build script.</p> <p>Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files.</p> <p>One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method. </p> <p>Something like (assuming the file created was called 'DateTime.dat'):</p> <pre><code>// I know Exceptions and proper open/closing // of the file are not done. This is just // to explain the point! String getBuildDateTime() { return new BufferedReader(getClass() .getResourceAsStream("DateTime.dat")).readLine(); } </code></pre> <p>To my mind that's a hack and could be circumvented/broken by someone having a similarly named file <em>outside</em> the JAR, but on the classpath.</p> <p>Anyway, my question is whether there is any way to inject a constant into a class at compile time</p> <p>EDIT</p> <p>The reason I consider using an externally generated file in the JAR a hack is because this <em>is</em>) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules.</p> <p>My personal preference would be to go with using the date from the JAR file as suggested by serg10.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload