简体   繁体   English

在运行时获取 Java 版本

[英]Getting Java version at runtime

I need to work around a Java bug in JDK 1.5 which was fixed in 1.6.我需要解决 JDK 1.5 中的 Java 错误,该错误已在 1.6 中修复。 I'm using the following condition:我正在使用以下条件:

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

Will this work for other JVMs?这是否适用于其他 JVM? Is there a better way to check this?有没有更好的方法来检查这个?

java.version is a system property that exists in every JVM. java.version是存在于每个 JVM 中的系统属性 There are two possible formats for it:它有两种可能的格式:

  • Java 8 or lower: 1.6.0_23 , 1.7.0 , 1.7.0_80 , 1.8.0_211 Java 8 或更低版本: 1.6.0_231.7.01.7.0_801.8.0_211
  • Java 9 or higher: 9.0.1 , 11.0.4 , 12 , 12.0.1 Java 9 或更高版本: 9.0.111.0.41212.0.1

Here is a trick to extract the major version: If it is a 1.x.y_z version string, extract the character at index 2 of the string.这里有一个提取主要版本的技巧:如果它是1.x.y_z版本字符串,则提取字符串索引 2 处的字符。 If it is a xyz version string, cut the string to its first dot character, if one exists.如果它是xyz版本字符串,则将该字符串剪切为其第一个点字符(如果存在)。

private static int getVersion() {
    String version = System.getProperty("java.version");
    if(version.startsWith("1.")) {
        version = version.substring(2, 3);
    } else {
        int dot = version.indexOf(".");
        if(dot != -1) { version = version.substring(0, dot); }
    } return Integer.parseInt(version);
}

Now you can check the version much more comfortably:现在您可以更轻松地检查版本:

if(getVersion() < 6) {
    // ...
}

What about getting the version from the package meta infos:从包元信息中获取版本怎么样:

String version = Runtime.class.getPackage().getImplementationVersion();

Prints out something like:打印出如下内容:

1.7.0_13 1.7.0_13

These articles seem to suggest that checking for 1.5 or 1.6 prefix should work, as it follows proper version naming convention.这些文章似乎建议检查1.51.6前缀应该有效,因为它遵循正确的版本命名约定。

Sun Technical Articles Sun 技术文章

Runtime.version()

从 Java 9 开始,您可以使用Runtime.version() ,它返回一个Runtime.Version

Runtime.Version version = Runtime.version();

The simplest way ( java.specification.version ):最简单的方法( java.specification.version ):

double version = Double.parseDouble(System.getProperty("java.specification.version"));

if (version == 1.5) {
    // 1.5 specific code
} else {
    // ...
}

or something like ( java.version ):或类似( java.version ):

String[] javaVersionElements = System.getProperty("java.version").split("\\.");

int major = Integer.parseInt(javaVersionElements[1]);

if (major == 5) {
    // 1.5 specific code
} else {
    // ...
}

or if you want to break it all up ( java.runtime.version ):或者如果你想把它全部分解( java.runtime.version ):

String discard, major, minor, update, build;

String[] javaVersionElements = System.getProperty("java.runtime.version").split("\\.|_|-b");

discard = javaVersionElements[0];
major   = javaVersionElements[1];
minor   = javaVersionElements[2];
update  = javaVersionElements[3];
build   = javaVersionElements[4];

Just a note that in Java 9 and above, the naming convention is different.请注意,在 Java 9 及更高版本中,命名约定是不同的。 System.getProperty("java.version") returns "9" rather than "1.9" . System.getProperty("java.version")返回"9"而不是"1.9"

Does not work, need --pos to evaluate double:不起作用,需要--pos来评估 double:

    String version = System.getProperty("java.version");
    System.out.println("version:" + version);
    int pos = 0, count = 0;
    for (; pos < version.length() && count < 2; pos++) {
        if (version.charAt(pos) == '.') {
            count++;
        }
    }

    --pos; //EVALUATE double

    double dversion = Double.parseDouble(version.substring(0, pos));
    System.out.println("dversion:" + dversion);
    return dversion;
}

Example for Apache Commons Lang: Apache Commons Lang 示例:

import org.apache.commons.lang.SystemUtils;

    Float version = SystemUtils.JAVA_VERSION_FLOAT;

    if (version < 1.4f) { 
        // legacy
    } else if (SystemUtils.IS_JAVA_1_5) {
        // 1.5 specific code
    } else if (SystemUtils.isJavaVersionAtLeast(1.6f)) {
        // 1.6 compatible code
    } else {
        // dodgy clause to catch 1.4 :)
    }

如果您可以依赖 apache utils,您可以使用 org.apache.commons.lang3.SystemUtils。

    System.out.println("Is Java version at least 1.8: " + SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8));

Here's the implementation in JOSM :这是JOSM 中的实现:

/**
 * Returns the Java version as an int value.
 * @return the Java version as an int value (8, 9, etc.)
 * @since 12130
 */
public static int getJavaVersion() {
    String version = System.getProperty("java.version");
    if (version.startsWith("1.")) {
        version = version.substring(2);
    }
    // Allow these formats:
    // 1.8.0_72-ea
    // 9-ea
    // 9
    // 9.0.1
    int dotPos = version.indexOf('.');
    int dashPos = version.indexOf('-');
    return Integer.parseInt(version.substring(0,
            dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
}

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. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties() ”暗示“java.version”是一个标准的系统属性,所以我希望它与其他 JVM 一起工作。

这是@mvanle 的答案,转换为 Scala: scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\\\.|_|-b") javaVerPrefix: String = 1 javaVerMajor: String = 8 javaVerMinor: String = 0

In kotlin:在科特林:

/**
 * Returns the major JVM version, e.g. 6 for Java 1.6, 8 for Java 8, 11 for Java 11 etc.
 */
public val jvmVersion: Int get() = System.getProperty("java.version").parseJvmVersion()

/**
 * Returns the major JVM version, 1 for 1.1, 2 for 1.2, 3 for 1.3, 4 for 1.4, 5
 * for 1.5 etc.
 */
fun String.parseJvmVersion(): Int {
    val version: String = removePrefix("1.").takeWhile { it.isDigit() }
    return version.toInt()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM