简体   繁体   English

IntelliJ:为什么我不能使用外部jar中的类

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

When I created the jar file I wrote the following java file: 创建jar文件时,我编写了以下Java文件:

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. 我将文件命名为MyClass.java。
  2. I created a class file by typing "javac src/main/java/myjar/MyClass.java" 我通过键入“ 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" 我通过以下命令生成了一个jar文件:“ jar cvf myjar.jar src / main / java / myjar / MyClass.class”

Now, I took the jar file and added it to Project Structure. 现在,我将jar文件添加到Project Structure中。 The name of the jar is 'myjar': 罐子的名称是“ myjar”: 在此处输入图片说明

and in the IDE I wrote "import myjar.MyClass" and the word 'myjar' was marked in red. 在IDE中,我写了“ import myjar.MyClass”,单词“ myjar”标记为红色。

When I use 'MyClass.hello()' in the project, I get an error: 当我在项目中使用'MyClass.hello()'时,出现错误:

no main manifest 没有主要表现

Do you know what I can to to load it successfully ? 你知道我能成功加载它吗?

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. 您只能将类路径中的库中的某些类导入Java源文件中,而不能导入整个Java归档(JAR)文件的内容。 So if you have inside myjar.jar file class Foo.class inside package (folder) bar, you can do 因此,如果您在包(文件夹)栏中的myjar.jar文件类Foo.class里面,可以

import bar.Foo;

After adding the .jar as a library in IntelliJ, you still need to add it to the module. 将.jar作为IntelliJ中的库添加后,您仍然需要将其添加到模块中。

在此处输入图片说明

Then the library will appear in the module's list of dependencies. 然后该库将出现在模块的依赖关系列表中。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM