Last active
November 30, 2017 10:06
-
-
Save nipafx/b193ced7985e4e76725d018020f4a269 to your computer and use it in GitHub Desktop.
Get the major Java version on Java 8 and earlier and on Java 9 and later
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* RELEASED UNDER CC-0 (https://creativecommons.org/publicdomain/zero/1.0/): | |
* | |
* You can copy, modify, distribute and perform the work, even for commercial | |
* purposes, all without asking permission. | |
*/ | |
import java.lang.reflect.Method; | |
public class JavaVersionSniffer { | |
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment