getClass().getClassLoader() is null, why?

Viewed 34587

I've got some code that calls..

x = getClass().getClassLoader();

This returns null though.

When I start the same code not from Eclipse, but the command line, it returns a classloader.

I can hack the code to do this...

if (getClass().getClassLoader() == null)
{
 x = ClassLoader.getSystemClassLoader().getSystemResourceAsStream( loadedPropFileName );
} 

both are compiled and run with the same JVM. (I'm 99.99% sure).

Anyone have any ideas why the first would return null for the classloader?

Edit:

My question is does "Anyone have any ideas why the same class would return null when started via Eclipse and a class loader when loaded from the command line."

Thanks for the advice that the Bootstap loader must be loading the class in Eclipse. I've no idea why this happens though.

8 Answers

Citing the API doc:

Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

Had similar issue. Solved by not using the getClass Method. Following worked for me.

<ClassName>.class.getClassLoader();

One thing is certain, Eclipse has a deeper and more complicated classloader setup than when you are running from the command line. If you are seeing differences in how a class's classloader appears in one versus the other then that is a pretty likely reason.

I'm not knowledgeable in what exactly Eclipse is doing but I think it very likely that your class is not being loaded by the bootstrap classloader when being run from Eclipse but that Eclipse is attempting to make it seem that way.

The bootstrap ClassLoader is static once the application is bootstrapped and you can't add jars or classes to it later unless Eclipse has overridden the implementation... in which case, there's yet another possible explanation.

It may be helpful, in order to know what Eclipse does exactly in terms of classpath setting, when launching an application, to click on the "Show Command Line" button under the application classpath setting. (I am using Eclipse 2020-06). For me, it showed that the jar file containing the class calling <ClassName>.class.getClassLoader(); which was returning null, was actually preceeded by
-Xbootclasspath/a:

Related