简体   繁体   中英

Cross-classloader class loading

I have a CustomClassLoader that loads classes from a Map<String, byte[]> . The classes that I am loading depend on other, unloaded classes. I have the jar files that contain said classes in a UrlClassLoader that is initiated before the CustomClassLoader , but when the CustomClassLoader tried to load a class that has an external import (a jarfile in the UrlClassLoader) an exception is thrown:

Exception in thread "main" java.lang.NoClassDefFoundError: external/class/in/urlclassloader/ClassImportedByLoadedClass
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
    at CustomClassLoader.defineClass(EncryptedByteArrayClassLoader.java:35)

I need some way to either:

a) load all the classes that are in the URLClassLoader

or

b) have some way to set the URLClassLoader as the default ClassLoader for the classes that are being loaded from memory (instead of my CustomClassLoader)

Line 35:

public Class<?> defineClass(String name, byte[] bytes) {
    return super.defineClass(name, bytes, 0, bytes.length);
}

I have tried setting the context ClassLoader like:

Thread.currentThread().setContextClassLoader(jarLoader);

where jarLoader is the URLClassLoader .

Is there any way to accomplish what I'm trying to do?

You should override ClassLoader(ClassLoader parent) constructor in your CustomClassLoader and pass your URLClassLoader there:

class CustomClassLoader extends ClassLoader {
     public CustomClassLoader(URLClassLoader parent, ...your data...) {
         super(parent);
         ...
     }
}

CustomClassLoader customClassLoader = new CustomClassLoader(jarLoader, ...);

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