Graal: Fix behavior of Class.getClassLoader() in native-image

Created on 26 Jul 2018  路  6Comments  路  Source: oracle/graal

The methods <class>.class.getClassLoader() or this.getClass().getClassLoader() return null when running as native-image.

That's allowed by JDK specification, but it denotes something that was loaded by Bootstrap Classloader only (e.g: java.lang.Object).

Looking at SVM code it says that getClassLoader should return null because the class was loaded by the system classloader, but in JDK system classloader never returns null.

Source: https://github.com/oracle/graal/blob/master/substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/hub/DynamicHub.java#L491

         /*
         * null is an allowed result value, denoting that the class was loaded by the system class
         * loader. This means we simulate a system where all classes are loaded by the system class
         * loader.
         */

That's how our applications and third party libraries / applications servers are built, they use getClass().getClassLoader() without checking for null (using Xbootclasspath is an exception).

In any case, I think the documentation should be clarified and the code fixed.
When calling it for JDK class, return null, when calling it for an application class (classpath), return ClassLoader.getSystemClassLoader().

I'm having a hard time trying to add substitutions for whole classes just because this null checks.

native-image

Most helpful comment

This should be fixed now. Feel free to try it out.

All 6 comments

This issue affects a large percentage of applications which use a HTML templating library, because they use a specific class's ClassLoader for scoping.

I confirm it also affects most Java EE code, leading to lots of NPEs there.

I am working on a fix. Will be in soon.

Sounds great!

I've coded a quick fix in subtratevm that returns a shared class loader that overrides enough methods to get me by, but a proper fix would be better :)

This should be fixed now. Feel free to try it out.

I tried it and I think it's fixed. I couldn't really verify further because I'm blocked by #603 now. But thanks!

Was this page helpful?
0 / 5 - 0 ratings