我正在用C#代码调用javac。最初我发现它的位置如下:

protected static string JavaHome
{
    get
    {
        return Environment.GetEnvironmentVariable("JAVA_HOME");
    }
}

但是,我刚刚在新计算机上安装了JDK,发现它没有自动设置JAVA_HOME环境变量。在过去十年中,要求环境变量在任何Windows应用程序中都是不可接受的,所以如果未设置JAVA_HOME环境变量,我需要一种方法来查找javac:

protected static string JavaHome
{
    get
    {
        string home = Environment.GetEnvironmentVariable("JAVA_HOME");
        if (string.IsNullOrEmpty(home) || !Directory.Exists(home))
        {
            // TODO: find the JDK home directory some other way.
        }

        return home;
    }
}
有帮助吗?

解决方案

如果您使用的是Windows,请使用注册表:

HKEY_LOCAL_MACHINE \ SOFTWARE \ JavaSoft \ Java Development Kit

如果你不是,你几乎坚持使用env变量。您可以找到博客入门很有用。

由280Z28编辑:

该注册表项下面是CurrentVersion值。该值用于在以下位置查找Java主目录:
HKEY_LOCAL_MACHINE \ SOFTWARE \ JavaSoft \ Java Development Kit \ {CurrentVersion} \ JavaHome

private static string javaHome;

protected static string JavaHome
{
    get
    {
        string home = javaHome;
        if (home == null)
        {
            home = Environment.GetEnvironmentVariable("JAVA_HOME");
            if (string.IsNullOrEmpty(home) || !Directory.Exists(home))
            {
                home = CheckForJavaHome(Registry.CurrentUser);
                if (home == null)
                    home = CheckForJavaHome(Registry.LocalMachine);
            }

            if (home != null && !Directory.Exists(home))
                home = null;

            javaHome = home;
        }

        return home;
    }
}

protected static string CheckForJavaHome(RegistryKey key)
{
    using (RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\JavaSoft\Java Development Kit"))
    {
        if (subkey == null)
            return null;

        object value = subkey.GetValue("CurrentVersion", null, RegistryValueOptions.None);
        if (value != null)
        {
            using (RegistryKey currentHomeKey = subkey.OpenSubKey(value.ToString()))
            {
                if (currentHomeKey == null)
                    return null;

                value = currentHomeKey.GetValue("JavaHome", null, RegistryValueOptions.None);
                if (value != null)
                    return value.ToString();
            }
        }
    }

    return null;
}

其他提示

您应该在注册表中搜索JDK安装地址。

作为替代方案,请参阅讨论。

对于64位操作系统(Windows 7),注册表项可能位于

HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ JavaSoft \ Java Development Kit

如果您正在运行32位JDK。因此,如果您已经根据上述内容编写了代码,请再次进行测试。

我还没有完全绕过 Microsoft注册表重定向/反射的东西。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top