To Documents

Working with JAR Files

Creating a JAR File from a Module

This section explains how to create a JAR file from a module.

  1. Create a IntelliJ Java project named JarTest.
  2. Add the two modules named personmodule and testmodule.
  3. To the module classes, add the class Person:
    public class Person {
        private String name;
        private char gender;
        private int age;
        
        public Person(String n, char g, int a) {
            name = n;
            gender = g;
            age = a;
        }
        
        @Override
        public String toString( ) {
            return String.format("%s %c %d",
                name, gender, age);
        }
    }
    
  4. To the module tests, add the class Test1:
    public class Test1 {
        
        public static void main(String[ ] args) {
            Person p = new Person("Alice", 'F', 11);
            System.out.println(p);
        }
    }
    
  5. Open the Project Structure dialog: File >> Project Structure.
  6. Select the Artifacts tab under Project Settings.
  7. Click the Add button ( + ) >> JAR >> From modules with dependencies.
    In the Create JAR from Modules dialog: select the module personmodule and leave the radio button "Extract to the target JAR checked." Click OK.
  8. To actually create the JAR file: select Build >> Artifacts >> classes:JAR >> Build. The JAR file personmodule.jar has been created in this folder:
    out/artifacts/personmodule_jar
    

Using a JAR File in a Module

This section explains how to add the JAR file as a dependency to the module testmodule.

  1. Open the Project Structure Window: File >> Project Structure.
  2. Select Modules under Project Settings.
  3. Select the Dependencies Tab. Select the module testmodule in the second column.
  4. On the far right of the Project Structure dialog, select the Add Button ( + ) >> JARs or Directories
  5. Select the JAR file classes.jar in the out/artifacts.personmodule_jar folder.
  6. Click OK. The tests module is now set to use the Person.class file via the personmodule.jar file.