Search code examples
javaclassresourcesclassloader

ClassLoader.getSystemResourceAsStream(className) returning null when trying to load class file resource


Class clazz = ...;
InputStream is = ClassLoader.getSystemResourceAsStream(clazz.getName().replace('.', '/') + ".class");

The input stream is returning null. I have used a simple java instrumentation agent to log classes as they are loaded and the class (clazz) is definitely being loaded by the ClassLoader. I've also tried

... Thread.currentThread().getContextClassLoader().getResourceAsStream(...));

and it returns null as well. What would be some possible causes for the resource not being able to be found by the class loader?


Solution

  • The Class has apparently been loaded by a different ClassLoader than the ones you're trying to find it with. Try this instead:

    InputStream is = clazz.getClassLoader().getResourceAsStream(
        clazz.getName().replace('.', '/') + ".class");
    

    Short of a flaw in the JVM, I don't think that can possibly return null.