Windows11下Java获取os版本返回Win10/10.0 求无命令实现代码
问题原因
- Windows 11的NT内核主版本号依然沿用10.0,你当前使用的Corretto 8u322版本JDK未适配Windows 11的识别规则,仅根据主版本号将系统判定为Windows 10,不会读取完整构建号做进一步判断。
- Windows 11正式版的起始内核构建(Build)号为22000,只要系统内核版本为10.0且Build号≥22000,即可判定为Windows 11,无需调用外部命令即可实现识别。
实现方案
采用JDK自带的Preferences API读取Windows注册表中存储的真实系统信息:
- Windows平台下JDK的
Preferences底层通过原生系统API直接访问注册表,不会启动任何外部进程执行cmd、powershell类系统命令,完全符合要求。 - 读取注册表路径
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion下的ProductName(产品名)、CurrentBuild(构建号)、UBR(修订号)字段,结合Build号阈值判断真实系统版本。 - 普通用户权限即可读取上述注册表项,无需管理员权限,读取失败时自动回退到
System.getProperty的原始结果,兼容非Windows平台。
如果允许升级JDK,直接将Corretto 8升级到8.332.08.1及以上版本,官方已经原生修复了Windows 11的识别问题,无需额外代码。无法升级JDK时可使用下面的示例代码。
示例代码
import java.util.prefs.Preferences; public class RealOsInfoUtil { private static final int WIN11_MIN_BUILD = 22000; private static final String WIN11_NAME = "Windows 11"; /** * 获取真实系统名称 */ public static String getRealOsName() { String rawName = System.getProperty("os.name"); if (!isWindows()) { return rawName; } try { Preferences winVerReg = Preferences.systemRoot() .node("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"); String productName = winVerReg.get("ProductName", rawName); int buildNum = Integer.parseInt(winVerReg.get("CurrentBuild", "0")); if (buildNum >= WIN11_MIN_BUILD) { if (productName.contains("Windows 10")) { productName = productName.replace("Windows 10", WIN11_NAME); } else if (!productName.contains(WIN11_NAME)) { productName = WIN11_NAME; } } return productName; } catch (Exception e) { return rawName; } } /** * 获取真实系统版本号 */ public static String getRealOsVersion() { String rawVersion = System.getProperty("os.version"); if (!isWindows()) { return rawVersion; } try { Preferences winVerReg = Preferences.systemRoot() .node("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"); int buildNum = Integer.parseInt(winVerReg.get("CurrentBuild", "0")); String revision = winVerReg.get("UBR", "0"); if (buildNum > 0) { return String.format("10.0.%d.%s", buildNum, revision); } } catch (Exception e) { // 读取失败时回退到原始值 } return rawVersion; } private static boolean isWindows() { return System.getProperty("os.name", "").toLowerCase().contains("windows"); } public static void main(String[] args) { System.out.println("os name = " + getRealOsName()); System.out.println("os version = " + getRealOsVersion()); } }
在Windows 11设备上运行上述代码,会正确输出类似如下结果:
os name = Windows 11 Pro os version = 10.0.22621.2428
内容的提问来源于stack exchange,提问作者Durgesh patidar
相关产品推荐
相关产品推荐

