CrazySynthax
CrazySynthax

Reputation: 14998

IntelliJ: Why can't I use a class from external jar

When I created the jar file I wrote the following java file:

package myjar;

public class MyClass {

    public static void hello() {
        System.out.println("hello");
    }

    public static void main(String[] args) {
        MyClass.hello();
    }
}
  1. I named the file MyClass.java.
  2. I created a class file by typing "javac src/main/java/myjar/MyClass.java"
  3. I generated a jar file by the command: "jar cvf myjar.jar src/main/java/myjar/MyClass.class"

Now, I took the jar file and added it to Project Structure. The name of the jar is 'myjar': enter image description here

and in the IDE I wrote "import myjar.MyClass" and the word 'myjar' was marked in red.

When I use 'MyClass.hello()' in the project, I get an error:

no main manifest

Do you know what I can to to load it successfully ?

Upvotes: 1

Views: 4264

Answers (2)

Luciano van der Veekens
Luciano van der Veekens

Reputation: 6577

After adding the .jar as a library in IntelliJ, you still need to add it to the module.

enter image description here

Then the library will appear in the module's list of dependencies.

enter image description here

Upvotes: 0

Kristjan Veskimäe
Kristjan Veskimäe

Reputation: 992

You can only import some classes from your libraries on classpath into a Java source file, not a contents of a whole Java archive (JAR) file. So if you have inside myjar.jar file class Foo.class inside package (folder) bar, you can do

import bar.Foo;

Upvotes: 3

Related Questions