Determine major Java version across all Java releases

Nicolai :

When determining the major Java version on Java 8 and before it was common to use the system property java.specification.version, drop 1., and parse the second digit:

  • on Java 8 this would yield "1.8" ~> "8" ~> 8
  • on Java 9 the same calls leads to NumberFormatException because the system property is "9"

What is a future-proof way to determine the major Java version? The goal is to get an int that can be if-ed or switch-ed over to decide which code path to take (e.g. in a library to activate a feature).

Nicolai :

Java 9 introduced the Runtime.Version class, which should hopefully be supported for some time to come. Pairing it with the old approach I got:

public static int getMajorVersion() {
    try {
        // use Java 9+ version API via reflection, so it can be compiled for older versions
        Method runtime_version = Runtime.class.getMethod("version");
        Object version = runtime_version.invoke(null);
        Method version_major = runtime_version.getReturnType().getMethod("major");
        return (int) version_major.invoke(version);
    // do not catch `ReflectiveOperationException` because it does not exist in Java <7
    } catch (Exception ex) {
        // before Java 9 system property 'java.specification.version'
        // is of the form '1.major', so return the int after '1.'
        String versionString = System.getProperty("java.specification.version");
        return Integer.parseInt(versionString.substring(2));
    }
}

(I release this code under CC-0: You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission.)

It works on my machine (haha), but I'm not sure whether this is the best solution, because I don't know whether either the new API or the system property have any corner cases that I'm not aware of.

See also Stephen's answer for why reducing the version to a single digit might not be a good idea in the first place.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470632&siteId=1