A POM dependency contains native libraries (DLLs inside a JAR file). How do I programmatically look up the path of the downloaded JAR file so I can pass it into "java.library.path"?
You can use the maven dependency plugin to copy the artifacts to a predefined path:
http://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-artifacts.html
If the DLL is inside the JAR, then you will need to copy it out to a directory before it can be loaded. (JARs that include native libraries usually do this themselves.) If your JAR isn't doing this, then you can use Class.getResourceAsStream() and write this to a directory that you've added to the java.library.path
.
For an example of this, see loadNativeLibrary in JNA. It uses this technique to load it's own library (a JNI library) from a JAR.
Since System.load()
can't load libraries from within a jar, you will have to use a custom loader which extracts the library to a temporary file at runtime. Projects With JNI discusses this approach and provide code for the custom loader.
Library loader
We now have our JNI library on the class path, so we need a way of loading it. I created a separate project which would extract JNI libraries from the class path, then load them. Find it at http://opensource.mxtelecom.com/maven/repo/com/wapmx/native/mx-native-loader/1.2/. This is added as a dependency to the pom, obviously.
To use it, call
com.wapmx.nativeutils.jniloader.NativeLoader.loadLibrary(libname)
. More information is in the javadoc forNativeLoader
.I generally prefer to wrap such things in a try/catch block, as follows:
public class Sqrt { static { try { NativeLoader.loadLibrary("sqrt"); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } /* ... class body ... */ }
An alternative would be to unpack the dependency, for example using dependency:unpack
.