The jar and its manifest
A jar is a zip with a manifest. The jar task writes one with the classes and the resources of the main source set, and the manifest is where a program says which class starts it. Two attributes are enough to make the archive runnable with java -jar, and both of them are one block in the build script.
The archive
settings.gradle
rootProject.name = 'shop'
build.gradle
plugins {
id 'java'
id 'application'
}
version = '1.0.0'
application {
mainClass = 'com.example.App'
}
jar {
manifest {
attributes(
'Main-Class': 'com.example.App',
'Implementation-Title': 'shop',
'Implementation-Version': version,
)
}
}
src/main/java/com/example/App.java
package com.example;
public final class App {
public static void main(String[] args) {
System.out.println("shop 1.0.0, packed");
}
}
gradle jar --console=plain --offline --no-daemon
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :jar
BUILD SUCCESSFUL in 13s
2 actionable tasks: 2 executed
jar tf lists the content of an archive. The first entry is the manifest, because a jar is a zip and the manifest is the first file in it:
jar tf build/libs/shop-1.0.0.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/example/
com/example/App.class
The attributes
unzip -p build/libs/shop-1.0.0.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Main-Class: com.example.App
Implementation-Title: shop
Implementation-Version: 1.0.0
Gradle writes Manifest-Version always, and the three attributes of the block above in the order they were declared. The Main-Class is the one Java reads with -jar; the other two are there for a tool that reads a jar without unpacking it. A long value is wrapped at 72 bytes with a leading space on the next line, a rule of the jar format rather than of Gradle.
java -jar
java -jar build/libs/shop-1.0.0.jar
shop 1.0.0, packed
No Gradle, no class path, one file. The program has no dependency here; with one, the jar would still run only if the dependency is next to it, because the manifest does not pack other jars. That is why the application plugin writes a distribution with a lib/ folder instead.
Related
- The application plugin and gradle run: the zip with the start scripts and the dependencies.
- Compiler options: the next block of the same build script.
- mvn package and java -cp: the same archive and the same manifest, written by Maven.
Article author: Arthur Isaev