Pregunta

Estoy llamando a javac desde el código C #. Originalmente encontré su ubicación solo como sigue:

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

Sin embargo, acabo de instalar el JDK en una computadora nueva y descubrí que no configuró automáticamente la variable de entorno JAVA_HOME. Requerir una variable de entorno es inaceptable en cualquier aplicación de Windows durante la última década, por lo que necesito una forma de encontrar javac si la variable de entorno JAVA_HOME no está establecida:

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;
    }
}
¿Fue útil?

Solución

Si estás en Windows, usa el registro:

HKEY_LOCAL_MACHINE \ SOFTWARE \ JavaSoft \ Java Development Kit

Si no lo estás, estás bastante atascado con las variables env. Puede encontrar este blog entrada útil.

Editado por 280Z28:

Debajo de esa clave de registro hay un valor de CurrentVersion. Ese valor se usa para encontrar la página principal de Java en la siguiente ubicación:
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;
}

Otros consejos

Probablemente debería buscar en el registro una dirección de instalación de JDK.

Como alternativa, consulte esta discusión.

Para el sistema operativo de 64 bits (Windows 7), la clave de registro puede estar bajo

HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ JavaSoft \ Java Development Kit

si está ejecutando un JDK de 32 bits. Entonces, si todos han escrito un código basado en lo anterior, haga la prueba nuevamente.

Todavía no tengo la cabeza completamente alrededor de redirección / reflexión del registro de Microsoft aún.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top