Application with JNI Library
You can open this sample inside an IDE using the IntelliJ native importer or Eclipse Buildship. |
This sample shows how a JVM application in Gradle can use a JNI library. The library has no dependencies, and the build has a minimal configuration.
In this sample, we are using a JNI library implemented in Java and C++ within an application implemented in Java; however, this applies to other JVM and native languages as well.
build.gradle
plugins {
id 'java'
id 'application'
}
import org.gradle.util.GradleVersion
application {
if (GradleVersion.current() >= GradleVersion.version('6.7')) {
mainClass = 'com.example.app.Main'
} else {
mainClassName = 'com.example.app.Main'
}
}
dependencies {
implementation project(':jni-library')
}
build.gradle.kts
plugins {
id("java")
id("application")
}
import org.gradle.util.GradleVersion
import org.gradle.api.plugins.JavaApplication
// Create a shim method to support newer Gradle version
fun JavaApplication.setMainClass(className: String) {
if (GradleVersion.current() >= GradleVersion.version("6.7")) {
val getMainClass = javaClass.getMethod("getMainClass")
val mainClass = getMainClass.invoke(this) as Property<String>
mainClass.set("com.example.app.Main")
} else {
mainClassName = "com.example.app.Main"
}
}
application {
setMainClass("com.example.app.Main")
}
dependencies {
implementation(project(":jni-library"))
}
To build the library:
$ ./gradlew run > Task :run Bonjour, World! BUILD SUCCESSFUL 6 actionable tasks: 6 executed
It’s also possible to build a distribution archive:
$ ./gradlew :distZip BUILD SUCCESSFUL 8 actionable tasks: 3 executed, 5 up-to-date $ ls ./build/distributions/*.zip ./build/distributions/jvm-application-with-jni-library.zip
It is possible to use the distribution on a system where the code wasn’t built, given the native component of the JNI library is supported on the platform:
$ mv ./build/distributions/jvm-application-with-jni-library.zip . $ ./gradlew clean BUILD SUCCESSFUL 2 actionable tasks: 2 executed $ unzip jvm-application-with-jni-library.zip -d . Archive: /Users/daniel/jvm-application-with-jni-library.zip creating: /Users/daniel/jvm-application-with-jni-library/ creating: /Users/daniel/jvm-application-with-jni-library/lib/ inflating: /Users/daniel/jvm-application-with-jni-library/lib/jvm-application-with-jni-library.jar inflating: /Users/daniel/jvm-application-with-jni-library/lib/jni-library.jar creating: /Users/daniel/jvm-application-with-jni-library/bin/ inflating: /Users/daniel/jvm-application-with-jni-library/bin/jvm-application-with-jni-library inflating: /Users/daniel/jvm-application-with-jni-library/bin/jvm-application-with-jni-library.bat $ ./jvm-application-with-jni-library/bin/jvm-application-with-jni-library Bonjour, World!
For more information, see JNI Library Plugin, C++ Language Plugin and Application Plugin reference chapters.