简体   繁体   中英

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM