Is there any way to define a constant value to Java at compile time

后端 未结 7 965
不知归路
不知归路 2020-12-18 22:59

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 differe

7条回答
  •  隐瞒了意图╮
    2020-12-18 23:05

    I would favour the standards based approach. Put your version information (along with other useful publisher stuff such as build number, subversion revision number, author, company details, etc) in the jar's Manifest File.

    This is a well documented and understood Java specification. Strong tool support exists for creating manifest files (a core Ant task for example, or the maven jar plugin). These can help with setting some of the attributes automatically - I have maven configured to put the jar's maven version number, Subversion revision and timestamp into the manifest for me at build time.

    You can read the contents of the manifest at runtime with standard java api calls - something like:

    import java.util.jar.*;
    
    ...
    
    JarFile myJar = new JarFile("nameOfJar.jar");    // various constructors available
    Manifest manifest = myJar.getManifest();
    Map manifestContents = manifest.getAttributes();
    

    To me, that feels like a more Java standard approach, so will probably prove more easy for subsequent code maintainers to follow.

提交回复
热议问题