The exported JAR does not work? Main class cannot be found in exported JAR?

I guess I don’t have a deep understanding of exporting JAR. Anyway, I don’t know how to use the interface and function of exporting JAR. But I finally figured out the right way.

Step 1: Add the build

The first thing to look at is the concept of an Artifact, which can be understood as a build. For example, an Android Studio build an Artifact as an APK file. Java programs can certainly build JARs.

In a Java or Kotlin Project, in the toolbar at the top of IDEA, find the Project Structure icon.

Or in, File-> Project Structures… You can also find it.

Click to open the Project Structure window.

Select Artifacts on the left side of the Project Structure window, click the plus sign on the right side and select JAR-> Empty as shown in the image below

On the right side of the window, an editable screen appears. As shown in the figure below, the red box at the top is the name of the JAR package to fill in, the red box at the bottom left indicates what is contained in the JAR package, and the red box at the bottom right indicates what can be put in.

Step 2: Add the Manifest

When nothing is added to the Jar, click xxx. Jar and the Add Manifest action button appears at the bottom.

Add the Main class and specify the Main class. As shown in the figure below:

Step 3: Add the contents of the JAR package

Now comes the most critical operation.

For the source code in the project, it is generally displayed as’ XXXX ‘Compile Output, and the operation for them is, right click, selectPut into Output Root.

For libraries that your project depends on, just right-click and selectExtract Into Output Root.

And you end up with something like this.

Step 4: Build

With the above steps, an Artifact is configured. We can execute it.

In the menu bar, Build-> Build Artifacts…

Click Build to Build.

The generated stuff should be in a directory like Output or Out or Build.

Try java-jar yourJar. Jar!