We load any native library by using
System.loadLibrary("hello")
Now I came to know that this library name refers to hello.dll for windows and libhello.so for unix based system.
So where these platform dependent changes happens?
Is JRE doing this?
Short answer: yes.
From the Javadoc for
loadLibrary
: "Loads the system library specified by the libname argument. The manner in which a library name is mapped to the actual system library is system dependent."System.mapLibraryName(libname)
will return what the mapped library name will be.This reflects the common conventions for library names:
lib
prefix in Linux and Mac OS X, no prefix in Windows, plus platform dependent file extension. Note that the extension for JNI libraries on Mac OS X isjnilib
, notdylib
as it is for other libraries. Also this mapping is not unique to the Java runtime,gcc ... -lhello
will also look forlibhello.so
(orlibhello.dylib
on Mac OS X).If you don't want the runtime to do this mapping, you'd have to determine the correct filename including the extension yourself and pass this to
loadLibrary
tl;dr
The platform dependent library name is built in native methods of the Java Virtual Machine. The actual algorithm simply prepends/appends a platform specific prefix/suffix to the name:
"hello"
->"hello.dll"
"hello"
"libhello.so"
"hello"
->"libhello.dylib"
Long version:
There are a couple of JDK Java methods which deal with loading libraries and/or library names:
The famous
System.loadLibrary
actually callsRuntime.loadLibrary
which callsClassLoader.loadLibrary
. In the end the implementations of these methods call the following native methods which translate the given library name into the platform specific name:The implementations of these native methods can be found in (link to the OpenJDK versions):
Both methods implement the same algorithm to build the actual library name, prepending the prefix
JNI_LIB_PREFIX
and appending the suffixJNI_LIB_SUFFIX
.In the end the macros
JNI_LIB_PREFIX
andJNI_LIB_SUFFIX
are defined in platform dependent include files, namely