È possibile aggiungere solo cartelle o file jar a un caricatore di classi. Quindi se hai un singolo file di classe, devi prima metterlo nella struttura di cartelle appropriata.
Here è un piuttosto brutto hack che si aggiunge alla SystemClassLoader in fase di esecuzione:
import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
public class ClassPathHacker {
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method
public static void addFile(File f) throws IOException {
addURL(f.toURL());
}//end method
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch
}//end method
}//end class
La riflessione è necessaria per accedere al metodo protetto addURL
. Questo potrebbe fallire se c'è un SecurityManager.
È lì e un modo per rimuovere un file jar? Oppure sostituirlo con una versione più recente? – dmarrazzo