1

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");
        }

    }

}
2
  • 1
    Provide your current System.out console output in the question Commented Feb 22, 2016 at 16:35
  • 1
    I get a feeling you are reinventing the wheel here. Exactly why would you need to manually load the jar-file? java --classpath not doing the trick? Commented Feb 22, 2016 at 17:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.