1

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 ?

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • 1
    Does this jar have `myjar` package? If not, create one, you can't import from the default package: http://stackoverflow.com/questions/2193226/how-to-import-a-class-from-default-package. – CrazyCoder May 07 '17 at 22:12
  • Yes. As you can see, class MyClass is inside myjar package – CrazySynthax May 07 '17 at 22:52
  • Check the jar structure, it should have `myjar/MyClass.class` and no other directories above, it also should have `myjar` directory, not just `MyClass.class` file in the root of the jar. – CrazyCoder May 08 '17 at 00:19

2 Answers2

3

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;
0

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

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30