I'm fairly new to gradle and groovy. Here is my task that generates JNI headers:
apply plugin: 'java'
apply plugin: 'application'
mainClassName = "com.my.example.HelloG"
task GenerateJniHeaders(dependsOn: 'classes') << {
def classpath = "build/classes/main"
def nativeIncludes = "src/native/include"
"javah -d ${nativeIncludes} -classpath ${classpath} ${mainClassName}".execute()
}
classes.finalizedBy GenerateJniHeaders
build.dependsOn GenerateJniHeaders
It works ok but I feel it's a bit ugly. How can I improve it? I appreciate any suggestions, especially those which help me remove variables hardcoded by me. I would also like to make this task more generic - now it only generates JNI header for main class but I would want to run it for all java files. Moreover when this task fails (e.g. classpath is wrong) it doesn't print any error message and build succeed, which is misleading.
You can run the application by executing the run task (type: JavaExec). This will compile the main source set, and launch a new JVM with its classes (along with all runtime dependencies) as the classpath and using the specified main class.
Gradle has a task type of type Exec with a command line property so it would be more appropriate to use it:
task generateJniHeaders(type:Exec) {
def classpath = sourceSets.main.output.classesDir
def nativeIncludes = "src/native/include"
commandLine "javah", "-d", nativeIncludes, "-classpath", classpath, "$mainClassName"
dependsOn classes
}
Note that this way everything in this task is a configuration rather than an action (if you're unfamiliar with Gradle's build lifecycle then a recommended reading would be this section in the user guide.
build.dependsOn GenerateJniHeaders
should be replaced by jar.dependsOn GenerateJniHeaders
classes.finalizedBy
is not needed at all. Note that finalizedBy
is usually used for cleanups as it execute even if the task fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With