Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

plugins - 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)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...