Question

The method DriverManager.getCallerClassLoader() in class java.sql.DriverManager is declared as native. I understand that all the class loaders references in an application are available in the current executing JVM. Also, my basic understanding about native method is that it's used to call the method defined in native libraries and they execute outside the JVM execution environment.

My question is, what is that needed by DriverManager.getCallerClassLoader() which requires its implementation to be native?

Was it helpful?

Solution

My basic understanding about native method is that its used to call the method defined in native libraries

This is correct, native methods represent calls of the code that is part of a natively compiled library

and they execute outside the JVM execution environment

That is what native methods typically do. That is, the native methods that Java users write. However, native methods are not limited in what they can do: once you're outside of JVM, you can do what you wish. In fact, Java's built-in classes such as Class<T>, heavily rely on the ability to do so, with dozens of native method sprinkled around their Java code.

One of these methods is package-private java.lang.Class<T>.getClassLoader0 (yes, with a zero). The implementation of ClassLoader.getCallerClassLoader ultimately refer to this method, which queries the internals of JVM to fetch the class loader.

Note that DriverManager cannot forward the call to ClassLoader.getCallerClassLoader, because that would return the DriverManager's class loader (because DriverManager would be the caller of getCallerClassLoader). It is not possible for the DriverManager to repeat the "magic" of ClassLoader's getCallerClassLoader either, because it is located in a different package (i.e. not in the java.lang), so Class<T>.getClasLoader0 is not accessible. That is why it is forced to move the getCallerClassLoader into the native territory, where the native code can obtain the calling class and fetch its class loader without restrictions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top