代码之家  ›  专栏  ›  技术社区  ›  Sam Harwell

如何以编程方式查找javac.exe?

  •  2
  • Sam Harwell  · 技术社区  · 16 年前

    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;
        }
    }
    
    3 回复  |  直到 16 年前
        1
  •  4
  •   Sam Harwell    16 年前

    如果您在Windows上,请使用注册表:

    HKEY\U本地\U机器\SOFTWARE\JavaSoft\Java开发工具包

    this 博客条目很有用。

    在该注册表项下面是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;
    }
    
        2
  •  1
  •   luvieere    16 年前

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

    作为替代方案,请参见 this 讨论

        3
  •  0
  •   tryingToBeClever    15 年前

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

    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit

    我还没有完全清醒过来 Microsoft registry redirection/reflection 东西还没有。

    推荐文章