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:
>\java\1.6\bin\javac Hello.java
It runs fine if I use a Java 1.6 JVM:
>\java\1.6\bin\java Hello
Hello from Java v1.6.0_11
But if I try to run it under Java 1.5, it doesn't run:
>\java\1.5\bin\java Hello
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
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:
>P:\java\1.4\bin\java Hello
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:
>\java\1.6\bin\javac -source 1.2 -target 1.2 Hello.java
>\java\1.4\bin\java Hello
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;
at javaranch.versionCheck.Hello.main(Hello.java:12)
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.