tags:

views:

55

answers:

3

I need to write version-independent java code, because of some bugs in JDK 1.5 which was fixed in JDK 1.6 now i use the following condition:

if (System.getProperty("java.version").startsWith("1.5.")) {
...
} else{
...
}

Is there another possibility to check this? Will it work for JVM from IBM?

+5  A: 

java.version is a standard property which exists in every VM.

There is just a tiny trick which might make your life easier: Search for the second dot and cut the string there. Then convert it to double. Now, you can check the version much more comfortably:

if (version >= 1.5) ...

You can put this into static code of a class so it runs only once:

public static double JAVA_VERSION = getVersion ();

static double getVersion () {
    String version = System.getProperty("java.version");
    int pos = 0, count = 0;
    for ( ; pos<version.length() && count < 2; pos ++) {
        if (version.charAt(pos) == '.') count ++;
    }
    return Double.parseDouble (version.substring (0, pos));
}
Aaron Digulla
It is ok for 1.5 but 1.6 is not precise as a floating point number.
Ha
FP precision aside, for the OP's needs the code provided should at least be (version > 1.5), not >=.To the OP: if you use your current String comparison do you need to check below 1.5 too?
Steven Mackenzie
@Ha: Maybe but `double version = 1.6` and `Double.parseDouble("1.6")` should still yield the same bit pattern, right? Since we don't do arithmetics on the number (only a simple compare), even == will work as expected.
Aaron Digulla
A: 

Don't know another way of checking this, but this: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties()" implies "java.version" is a standard system property so I'd expect it to work with other JVMs.

Tom
+2  A: 

These articles seem to suggest that checking for 1.5 or 1.6 prefix should work, as it follows proper version naming convention.

Sun Technical Articles

polygenelubricants