Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine major Java version across all Java releases

Tags:

java

java-9

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).

like image 809
Nicolai Parlog Avatar asked Nov 13 '17 09:11

Nicolai Parlog


1 Answers

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.

like image 178
Nicolai Parlog Avatar answered Sep 16 '22 15:09

Nicolai Parlog