Come trovo javac.exe a livello di codice?
-
06-07-2019 - |
Domanda
Sto chiamando javac dal codice C #. Inizialmente ho trovato la sua posizione solo come segue:
protected static string JavaHome
{
get
{
return Environment.GetEnvironmentVariable("JAVA_HOME");
}
}
Tuttavia, ho appena installato JDK su un nuovo computer e ho scoperto che non impostava automaticamente la variabile d'ambiente JAVA_HOME. Richiedere una variabile di ambiente è inaccettabile in qualsiasi applicazione Windows negli ultimi dieci anni, quindi ho bisogno di un modo per trovare javac se la variabile di ambiente JAVA_HOME non è impostata:
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;
}
}
Soluzione
Se sei su Windows, usa il registro:
HKEY_LOCAL_MACHINE \ SOFTWARE \ JavaSoft \ Java Development Kit
Se non lo sei, sei praticamente bloccato con le variabili env. Puoi trovare questo blog voce utile.
Modificato da 280Z28:
Sotto quella chiave di registro c'è un valore CurrentVersion. Tale valore viene utilizzato per trovare la home Java nella seguente posizione:
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;
}
Altri suggerimenti
Probabilmente dovresti cercare nel registro un indirizzo di installazione JDK.
In alternativa, vedi questa discussione.
Per sistemi operativi a 64 bit (Windows 7), la chiave di registro potrebbe trovarsi in
HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ JavaSoft \ Java Development Kit
se stai utilizzando un JDK a 32 bit. Quindi, se hai scritto tutto il codice in base a quanto sopra, prova di nuovo.
Non ho ancora completamente compreso la mia Reindirizzamento / riflessione del registro Microsoft roba ancora.