Gradle Cheat Sheet (9): Applying the Java plugin
在Gradle中启用Java插件,只需在编译脚本中加入:
apply plugin: "java"
此时运行:
$ gradle tasks --all
会看到多出许多任务,常用的有assemble 、check 、build 和clean :
Task name | Depends on | Type | Description |
assemble | All archive tasks in the project, including jar. Some plugins add additional archive tasks to the project. | Task | Assembles all the archives in the project. |
check | All verification tasks in the project, including test. Some plugins add additional verification tasks to the project. | Task | Performs all verification tasks in the project. |
build | check and assemble | Task | Performs a full build of the project. |
clean | – | Delete | Deletes the project build directory. |
以这里提供的代码为例,在\src\main\java\com\udacity\gradle下有一个Person.java文件,内容如下:
package com.udacity.gradle; public class Person { private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } public static void main(String[] args){ System.out.println("Hello from Java"); } }
此时运行:
$ gradle assemble
看到输出:
BUILD SUCCESSFUL
此时就可以在build文件夹下找到编译输出。
Gradle提供了JavaExec 来运行代码:
task execute(type: JavaExec) { main = "com.udacity.gradle.Person" classpath = sourceSets.main.runtimeClasspath }
运行:
$ gradle execute
输出为:
Hello from Java
Java插件默认Java代码放在\src\main\java\下面,如果想要加入其它位置的代码,可以修改sourceSets ,如:
sourceSets { main { java { srcDir 'java' } } }
这样会把与build.gradle同目录的java文件夹下的代码也加入到编译中。
还可以通过类似方法修改其它任务的属性,如为jar 任务添加名为Implementation-Version 的manifest 属性,值为“1.0”:
jar { manifest { attributes 'Implementation-Version': '1.0' } }
完整代码可以在这里找到。
更多内容可以参考相关文档和教程:Java Quickstart,The Java Plugin和JavaExec。