简体   繁体   中英

Java classloader, what should I do for the loaded classes class dependencies?

For example, I am loading a class from a byte array.

Lets assume this class is being loaded:

package loadedclass;


public class LoadedClass {
    public void out(String msg) {
        LoadedClass2 lc2 = new LoadedClass2();
        lc2.printMsg();
        System.out.println(msg);
    }
}

And lc2 is another class which prints messages.

Now, if I load LoadedClass from my byte stream classloader, what should I do about LoadedClass2 that LoadedClass depends on?

Will I basically have to make LoadedClass load LoadedClass2 in its constructor, or something?

Is there a cleaner way to do this so that I can load all classes that LoadedClass depends on from my class loader?

No you do not have to manually load the dependent LoadedClass2 as it will dynamically be loaded using your own Byte Stream Class loader.

For more on Java Class Loading .

You will just have to provide the root class that you have to load and all the other dependencies java will dynamically try to resolve using the classloaders hierarchy.

In your case the Byte Stream Class loader will get call for findClass() for two classes LoadedClass and LoadedClass2 without calling explicitly for LoadedClass2 .

You can check that by keeping a println() in the findClass() method.

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