简体   繁体   English

URLClassLoader getResourceAsStream 返回 null

[英]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.我的项目中有一个自定义ClassLoader ,它加载一个在运行时从用户输入动态生成的类。 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.为了构建它,我通常遵循本教程中的说明,但使用URLClassLoader作为父级,因为类可能会在运行时更改。

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.它可以很好地加载类本身,但是一旦它尝试加载关联的类,它就会在以下代码的第 4 行 ( stream.available() ) 抛出NullPointerException ,因为返回的流为空。

//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.使用getResourceAsStream()的默认类加载器似乎没有帮助。

Java 11 onwards if URLClassLoader is returned null it throws NullPointerException.从 Java 11 开始,如果 URLClassLoader 返回 null,则会引发 NullPointerException。

refer:参考:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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