简体   繁体   中英

How to embed Java code into Gradle build using JavaExec task

I have a Gradle-driven project to which I want to add a simple Java task. This task is very specific to the project and if it can be helped I don't want to develop it as a separate plugin. So the question is can I define such custom task within the same build.gradle I'm using for my project? Or is it inevitable that I need to package it as a separate project (plugin) and install to the local repo?

Also it's probably important to note that the original project is not Java related (no other Java code needs to be build)

PS Based on comments below:

I would like to add src/main/java/SomeUsefulStuff.java to the existing project and have that file compiled and used as a custom task. I do understand that it needs to be compiled each time I run the build but again - the code will be small. However it will have some external dependencies such as Commons IO

Thanks to RaGe who pointed to JavaExec this turned out to be pretty simple. Here's what you do:

  1. Put your Java code in /src/main/java just as you would in the regular Gradle-driven Java project. Make sure it has main method in the file you are going to call
  2. Add apply plugin: 'java' to the build.gradle
  3. If your Java code has any dependencies on 3rd party libs add these to dependencies section
  4. Add new task section to build.gradle like so:
 task usefulStuff(type: JavaExec) { classpath = sourceSets.main.runtimeClasspath main = 'com.me.gradle.UsefulStuff' // arguments to pass to the application args 'OhmyGod!' }
  1. Now you can refer to that task as any task in your build. For example imporantTask.dependsOn usefulStuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM