はっきり理解してなかったのですが、jarファイルを実行した際に、「メイン・マニフェスト属性がありません」とのエラーが出ることがあります。
testusers@testusers-mac libs % ls
slotmachineXYZ-1.0-SNAPSHOT.jar
testusers@testusers-mac libs % java -jar slotmachineXYZ-1.0-SNAPSHOT.jar
slotmachineXYZ-1.0-SNAPSHOT.jarにメイン・マニフェスト属性がありません
testusers@testusers-mac libs %
出たり出なかったりで、このエラーの意味するところをキチンと理解してなかったのですが、今回、腰を据えてキチンと調べました。
Chatgptに聞いたところ、下記の様に原因を答えてきました。
When you run into the error:
メイン・マニフェスト属性がありません
(English: “No Main Manifest Attribute”)
it means your JAR file does not have a Main-Class entry in its manifest. A runnable (executable) JAR needs two things:
1. A main method in one of your classes.
2. The JAR’s manifest must declare which class contains the main method.
Since your slotmachineXYZ class has main, you just need to configure Gradle to specify that org.example.slotmachineXYZ is the main class.
要は、2つの原因が考えれる。
一つは、mainクラスがない。(今回は、ちゃんとあるので、これではない。)
もう一つは、どこにmainクラスが含まれているかを、Manifestに明示した上で、JarでGradle Buildしないといけない。(今回はこちら。)
Chatgptに聞くと、Manifestに明示する方法として、下記の2つが明示されております。
1)Use the Gradle application Plugin (自動化バージョン)
An easy solution is to use the application plugin. In your build.gradle (at the top level):
plugins {
id 'java'
id 'application'
}
group 'org.example'
version '1.0-SNAPSHOT'
application {
mainClass = 'org.example.slotmachineXYZ'
}
2)Or Manually Configure the JAR Manifest (マニュアルバージョン)
If you don’t want to use the application plugin, you can add a jar task that explicitly sets the main class attribute in your build.gradle:
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
jar {
manifest {
attributes(
'Main-Class': 'org.example.slotmachineXYZ'
)
}
}
Then build again:
./gradlew jar
This will produce a JAR with a Main-Class specified in its manifest. You can then run:
java -jar build/libs/<your-jar-name>.jar
要は、“No Main Manifest Attribute”って、どこにMainクラスがあるか、分からないから、きちんとManifestに明示してから、ビルドせよと言う事。