mburke13
mburke13

Reputation: 500

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?

Upvotes: 0

Views: 1176

Answers (2)

Saurabh
Saurabh

Reputation: 7964

Did you try getClass().getClassLoader().getResourceAsStream() Please make sure that the class file you tru to load in in classpath of your code. Also couild you please share the value of clazz.getName() ?

EDIT:

Are you doing something like following ?

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

I mean to say that do you define clazz as ClassName.class ? If not then try doing this and then see.

Upvotes: 1

Ryan Stewart
Ryan Stewart

Reputation: 128779

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.

Upvotes: 2

Related Questions