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?
This is correct, native methods represent calls of the code that is part of a natively compiled library
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 ofnativemethod sprinkled around their Java code.One of these methods is package-private
java.lang.Class<T>.getClassLoader0(yes, with a zero). The implementation ofClassLoader.getCallerClassLoaderultimately refer to this method, which queries the internals of JVM to fetch the class loader.Note that
DriverManagercannot forward the call toClassLoader.getCallerClassLoader, because that would return theDriverManager‘s class loader (becauseDriverManagerwould be the caller ofgetCallerClassLoader). It is not possible for theDriverManagerto repeat the “magic” ofClassLoader‘sgetCallerClassLoadereither, because it is located in a different package (i.e. not in thejava.lang), soClass<T>.getClasLoader0is not accessible. That is why it is forced to move thegetCallerClassLoaderinto thenativeterritory, where the native code can obtain the calling class and fetch its class loader without restrictions.