简体   繁体   中英

URLClassLoader getResourceAsStream returns null

I have a custom ClassLoader in my project, that loads a class that is dynamically generated from user input at runtime. For building it I generally followed the instructions from this tutorial here but instead used a URLClassLoader as a parent as the class may change at runtime.

It works fine for loading the class itself, but as soon as it tries to load associated classes it throws a NullPointerException at line 4 ( stream.available() ) in the following code, as the returned stream is null.

//file is "java\lang\Object.class" when throwing the exception
private byte[] loadClassFileData(String file) throws IOException { 
    InputStream stream = parent.getResourceAsStream(file);
    int size = stream.available();
    byte buff[] = new byte[size];
    DataInputStream in = new DataInputStream(stream);
    in.readFully(buff);
    return buff;
}

Using the default class loader for getResourceAsStream() doesn't seem to help.

Java 11 onwards if URLClassLoader is returned null it throws NullPointerException.

refer:

https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8198803

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