Home > OS >  URLClassLoader trying to get a class from external jar always returning null
URLClassLoader trying to get a class from external jar always returning null

Time:08-24

I am trying to load a class from a jar that is sitting in a directory. The structure of the class I am trying to grab is as follow:

myapp.jar
|__META-INF
|__com
   |__myapp
      |__config
         |__PlumberConfig.class

This is how I tried to grab the class:

        File file = new File("C:/_workspace/_jar/myapp.jar");
        URL url = file.toURI().toURL();
        URL[] urls = new URL[]{url};

        URLClassLoader ucl = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
        LOG.info("URLClassLoader: {}", ucl.getName()); // here always null
        Class c = ucl.loadClass("com.myapp.config.PlumberConfig");

The result of new URLClassLoader() is always null hence I cannot go further from this point.

I double-checked everything (the path, name of the jar, and location of the class itself) but seems I am still missing something.

CodePudding user response:

Your code is working but the method getName() is not defined on URLClassLoader. Try ucl.getURLs() instead. Than it should work as expected.

  • Related