I'm developing a small utility lately that can be both executed in cmd line environment or as a GUI if no args are passed.
Now I'd like to test if the user as the right JRE before running everything in order to display an error message!
I found some code to get the JRE version but is there a better way of doing it (if version higher than 1.6 than OK else error message).
That will work. But there are a couple of things to keep in mind.
1) A compiled class will not run under an older JVM, even if that class does not use anything specific to the later JVM. Take for example this simple class:
All the classes and methods it uses have been around since the early days of Java. If I compile it via Java 6:
It runs fine if I use a Java 1.6 JVM:
Hello from Java v1.6.0_11
But if I try to run it under Java 1.5, it doesn't run:
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.security.AccessController.doPrivileged(Native Method)
That "Bad version number" means that I am trying to run newer code with an older JVM.
To solve this, I can compile the code using the source and target switch on the compiler:
>\java\1.6\bin\javac -source 1.2 -target 1.2 Hello.java
Now it will run fine under an older JVM:
Hello from Java v1.4.2_18
If any subsequent code uses a Java 6 feature, an Exception would get thrown. For example, here I use the Console class and System.getConsole() method added in Java 6:
Hello from Java v1.4.2_18
Your code would stop executing here if the Java version was not correct
Exception in thread "main" java.lang.NoSuchMethodError: java.lang.System.console()Ljava/io/Console;
One thing you can do which might make life easier is to write a Version checking class that after verifying the version calls a starter method in another class. Then you only need to worry about setting the source and target when you compile this version check class.
2) The second thing to keep in mind that this will return a string like "1.6.0_11". So you'll need to break up the string so that you can get the major and minor parts and compare them. (And if the micro and patch levels are important, you'll need to do that as well.) You can use String manipulation to do this such as indexOf(".") and indexOf("_"). Or you can use a regular expression to break it up:
Hope that helps.
Joined: Jan 22, 2007
MANY THANKS Mark for such a complete and instructive reply!
I really did not know about the 1st point indeed.
Regarding the second point I'll make pleasure parsing version string with some regex! By the way my favorite regex class is the Jakarta ORO one (Perl5Util)!