Reputation:
I need load a jar file in runtime in Java and I have this code but it not load any jar and I don't know how, somebody can tell me why? I have JVM 8 and NetBeans 8, the purpose is create a program that can load jar files as a plugins y for Windows.
package prueba.de.classpath;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class PruebaDeClasspath {
public static void main(String[] args) {
try {
Class.forName("PluginNumeroUno");
} catch (ClassNotFoundException e) {
System.out.println("Not Found");
}
try {
URLClassLoader classLoader = ((URLClassLoader) ClassLoader
.getSystemClassLoader());
Method metodoAdd = URLClassLoader.class.getDeclaredMethod("addURL",
new Class[]{URL.class});
metodoAdd.setAccessible(true);
File file = new File("plugins/PrimerPlugins.jar");
URL url = file.toURI().toURL();
System.out.println(url.toURI().toURL());
metodoAdd.invoke(classLoader, new Object[]{url});
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName("PluginNumeroUno");
System.out.println("ok");
} catch (ClassNotFoundException e) {
System.out.println("Not Found");
}
}
}
Upvotes: 1
Views: 445
Reputation: 7620
Try creating new class loader instead of casting the system classloader.
Remove this line:
URLClassLoader classLoader = ((URLClassLoader) ClassLoader.getSystemClassLoader());
and create the new loader and use it as below:
File file = new File("plugins/PrimerPlugins.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()},
PruebaDeClasspath.class.getClassLoader());
Class.forName("prueba.de.classpath.PluginNumeroUno", true, classLoader); //fully qualified!
Please note that the class name to be loaded has to be fully qualified.
You also don't have to dynamically force addURL()
to be public.
Upvotes: 1