简体   繁体   中英

Check whether the cureent JVM is 64 bit or 32 bit

After some research on the same topic, I used the method "getVersion()" to check whether a JVM is 64 bit or 32 bit.

 public static String getVersion()
 {
   String version = System.getProperty("sun.arch.data.model");
   if (version != null && version.contains("64")){
       return "64";
   }else{
       return "32";
   }
 }

It went wrong in some cases. Yes as the flag name mentions, the method is clearly sun-dependent. I tried getting the property "os.arch" also. But in some cases, it is wrongly identifying JVM. Is there any more trustable way of checking the same? My application is purely based on windows. And I don't want the method to work on any other platforms.

You will need the 2 jar files from here : https://java.net/projects/jna/downloads/directory/3.3.0

( Code edited to fix evaluation of IsWow64Process)

import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.ptr.IntByReference;

public class Main {

    public static void main(String[] args) {
        System.out.println(is64BitJava());
    }

    private static boolean is64BitJava(){
        if (!is64BitWindows()){
            return false;
        }

        Kernel32 kernel32 = Kernel32.INSTANCE;
        WinNT.HANDLE handle = kernel32.GetCurrentProcess();
        if (!kernel32.IsWow64Process(handle, ref)){
            return false;
        }

        return ref.getValue() == 0;

    }

    private static boolean is64BitWindows(){
        String envVar = System.getenv("ProgramW6432");
        if (envVar == null){
            envVar = "";
        }

        return envVar.length() > 0;
    }

}

In order to check if Windows is 64 bit, I check if ProgramW6432 environment variable is defined.

Then I use Win32 API GetCurrentProcess and IsWow64Process functions to examine current running process.

Here is a pure Java solution that checks the ability to link 32-bit library into the current process:

static boolean is64bitProcess() {
    String wow64_kernel = System.getenv("systemroot") + "\\SysWOW64\\kernel32.dll";
    if (new File(wow64_kernel).exists()) {
        try {
            System.load(wow64_kernel);
        } catch (UnsatisfiedLinkError e) {
            return true; // can not link 32-bit library into 64-bit process
        }
    }
    return false;
}

检查这个

 System.out.println(System.getProperty("os.arch"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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