Picocli | Create your first Kotlin /JVM CLI application with GraalVM

Setup Environment

First of all, we need to create a new Kotlin project with Gradle as a build system. The easiest way to do that is by clicking through the Project window in IntelliJ IDEA.

  1. Add picocli-codegen as kapt (kotlin-annotation-processor)
  2. Add picocli as an implementation
  3. Create kapt block with the argument project.
  4. Configure the jar file output by setting a manifest with the attribute Main-Class. In my case it is CheckSumKt.
  5. Exclude the META-INF files from the classpath.
  6. Enable Annotation Processors in intelliJ. Docs here

Create the CheckSum class

This file has a special syntax, the Command annotation defines the name of the command, which should be called finally. It also defines, the version and if it should generate a help option.

Build and start the Application

To build the application, you just have to use a normal gradle command:

$ ./gradlew clean build
$ java -jar build/libs/picocli-test-1.0.jar
echo "export PATH=$PATH:$(pwd)" >> ~/.zshrc
echo "alias checksumjar='java -jar $(pwd)/build/libs/picocli-test-1.0.jar'" >> ~/.zshrc

Native with GraalVM

To use GraalVM, you have to download it first via homebrew:

$ brew install graalvm-ce-java8
$ cd /Library/Java/JavaVirtualMachines/graalvm-ce-java8-      21.0.0/Contents/Home$ ./bin/gu install -L /bin/native-image
$ $GRAAL_HOME/native-image -cp classes:build/libs/picocli-test-1.0.jar --no-server  -H:Name=checksum CheckSumKt
$ ./checksum

Why GraalVM?

Why to make this extra step? Simple! The file runs now native on Linux and MacOS and is blazing fast. It does not need the JVM anymore installed and is now immutable to wrong java versions on client side.

Speed difference:

Developer Experience Engineer