Search code examples
javajarurlclassloader

Java URLClassLoader: select which classes to import


Currently I'm using this line to load a 3rd party JAR and add its packages/classes to my program

URL [] urls = new URL [] { "http://..." };
new URLClassLoader(urls);

The problem I have with this approach is that the whole JAR is loaded, meaning all packages and all classes are imported. How can I tell URLClassLoaded to load only a few selected classes?

An example would be a JAR hierarchy like this

  • package A
    • class 1
    • class 2
  • package B
    • class 1
    • class 2
    • class 3
    • class 4

I'd like to do something like "import only A.* and B.class2"


Solution

  • Provide a custom implementation of ClassLoader.

    Override the findClass() method of the classloader and apply the business logic for selecting the classes that you want to be loaded.

    class CustomClassLoader extends ClassLoader {
    
             public Class findClass(String name) {
                 if(shouldBeLoaded)
                    return defineClass(name, b, 0, b.length);
             }
        }
    

    Setting this as the default class loader for loading (optional)

    java -Djava.system.class.loader
        =com.test.CustomClassLoader