Skip to content

Instantly share code, notes, and snippets.

@nipafx
Last active November 30, 2017 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nipafx/b193ced7985e4e76725d018020f4a269 to your computer and use it in GitHub Desktop.
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
/*
* 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