Reputation: 113
I would like to define a version number in a main class in each jar file that is assigned at compile time, like what can be easily done in C with an #include statement with a value from an external file. I would like to only set a value in that external location once, so any jar files that get compiled/built until I change it gets that same value.
My first thought was to define it in a common class then simply reference it like this:
I create a Base.java file:
class Base
{
public final static String version = "1.2.3";
}
Then I compile Base.java and jar it up.
And then I create a Module1.java file:
class Module1
{
public final static String version = Base.version;
public static void main( String[] args )
{
Module1();
}
Module1()
{
System.out.println( "Module1: "+this.version );
}
}
But of course, this won't compile without importing Base class, so I insert this just before the Module1 class:
import Base;
And I compile Module1.java and jar it up, and execute it; and as expected it returns:
Module1: 1.2.3
So far so good. But then I edit the Base.java file and change the version value to something different, like, say, "1.3.0", then compile Base.java and jar it up.
And now I want to create a Module2.java file:
import Base;
class Module2
{
public final static String version = Base.version;
public static void main( String[] args )
{
Module2();
}
Module2()
{
System.out.println( "Module2: "+this.version );
}
}
And I compile and jar up Module2, and execute it it correctly returns:
Module2: 1.3.0
Also good. But as a sanity check I expect (want/hope) Module1 to return the same results as before, so I rerun Module1, but Bogus! It returns:
Module1: 1.3.0
Any advice on how to pull this off? So the version in a module remains as it was at compile-time, not set during each session at run-time?
Upvotes: 0
Views: 585
Reputation: 97288
In Java, the standard place for storing the version of a .jar file is the manifest file (META-INF/MANIFEST.MF), not a class file. Specifically, put this line there:
Implementation-Version: 1.2.3
See here for more details.
To access this information from your code, use the java.util.jar.Manifest class, and specifically the getMainAttributes() method.
Upvotes: 1