How to embed Java code into Gradle build using JavaExec task

时光总嘲笑我的痴心妄想 提交于 2020-05-29 07:29:49

问题


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)

P.S. 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


回答1:


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


来源:https://stackoverflow.com/questions/36071615/how-to-embed-java-code-into-gradle-build-using-javaexec-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!