Skip to content

Instantly share code, notes, and snippets.

@devlights
Created September 30, 2024 09:47
Show Gist options
  • Save devlights/633ebbe8cecf8647cbdb4754d85c3572 to your computer and use it in GitHub Desktop.
Save devlights/633ebbe8cecf8647cbdb4754d85c3572 to your computer and use it in GitHub Desktop.
[Java] モジュール形式でjarファイルまで作成する手順 (IDEを使わずに)

Java

$ java -version
openjdk version "23" 2024-09-17
OpenJDK Runtime Environment Temurin-23+37 (build 23+37)
OpenJDK 64-Bit Server VM Temurin-23+37 (build 23+37, mixed mode, sharing)

手順

#
# プロジェクト構造作成
#
$ mkdir -p app/src/com/example
$ cd app

#
# module-info作成
#
$ cat src/module-info.java << EOF
module com.example {
  requires java.base;
}
EOF

#
# メインクラス作成
# 
$ cat src/com/example/Main.java << EOF
package com.example;
public class Main {
  public static void main(String[] args) {
    System.out.println("hello world");
  }
}
EOF

#
# コンパイル
#
$ javac -d mods/com.example src/module-info.java src/com/example/Main.java

#
# 実行
#
$ java --module-path mods -m com.example/com.example.Main

#
# JARファイルの作成
#
$ mkdir -p META-INF
$ echo "Main-Class: com.example.Main" > META-INF/MANIFEST.MF
$ jar --create --file=com.example.jar --manifest=META-INF/MANIFEST.MF -C mods/com.example .

#
# JARファイルの実行
#
$ java --module-path com.example.jar -m com.example/com.example.Main
hello world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment