无法从jar导入类

时间:2018-08-13 13:28:34

标签: java spring maven import jar

在将类从JAR库导入到我的项目时遇到问题。请查看屏幕截图。

我已经在Eclipse和IntelliJ中尝试了几件事,直接添加和通过Maven添加。这些都无济于事,下划线仍然是红色。

我在IntelliJ中尝试过:

  1. 项目结构-模块-依赖关系-添加jar。
  2. 尝试创建一个lib文件夹,将其添加为库,然后将jar放入其中,然后将其设置为依赖项。
  3. 通过maven pom.xml添加到jar的直接路径。

在Eclipse中,我尝试过:

  1. Java构建路径并将其添加到我的构建路径。
  2. Maven-更新项目。

这是我的pom.xml,用于获取本地jar。

<dependency>
  <groupId>uk.co.pervasive_intelligence.simulator</groupId>
  <artifactId>protocol</artifactId>
  <version>1.0</version>
  <scope>system</scope>
  <systemPath>C:\Users\Vas-DELL\Desktop\simulator-1.2.2.jar</systemPath>
</dependency>

奇怪的是,我能够看到jar和jar中的类(截图)。但是仍然无法导入它们。让我知道是否还有其他可以提供的东西。

Screenshot

3 个答案:

答案 0 :(得分:2)

在项目文件夹的根目录中创建一个lib /目录。把你的罐子放在那里。将此添加到您的pom.xml:

<dependency>
  <groupId>uk.co.pervasive_intelligence.simulator</groupId>
  <artifactId>protocol</artifactId>
  <version>1.0</version>
  <scope>system</scope>
  <systemPath>${basedir}/lib/simulator-1.2.2.jar</systemPath>
</dependency>

请勿使用\作为路径分隔符(即使您使用的是Windows)

从命令行运行mvn clean package

您还可以尝试在本地存储库中手动安装Dependecy:

mvn install:install-file -Dfile=simulator-1.2.2.jar -DgroupId=uk.co.pervasive_intelligence.simulator -DartifactId=protocol -Dversion=1.0 -Dpackaging=jar

然后将其添加到您的pom:

<dependency>
  <groupId>uk.co.pervasive_intelligence.simulator</groupId>
  <artifactId>protocol</artifactId>
  <version>1.0</version>
</dependency>

编辑:

jar文件没有标准Java库的结构。为了将该jar用作库,您的类的程序包应作为文件夹存在于jar文件的基础(或根目录)中。例如:

/META-INF
    /MANIFEST.MF
/uk
    /co
        /pervasive_intelligence
            /simulator
                /BaseComponent.class
                /SimulatorApplication.class
                /SimulatorException.class
....

作为一个库jar文件,MANIFEST.MF的内容可以很简单

Manifest-Version: 1.0

希望这会有所帮助

答案 1 :(得分:1)

co.uk ... 包中的

Class文件位于 simulator jar中的 BOOT-INF / classes 内,无法访问直接因为它不是jar的默认类路径(“。”)的一部分。

要更好地了解jar类路径,请检查What's the default classpath when not specifying classpath?

模拟器 jar需要与类路径条目打包在一起,以在类路径中添加BOOT-INF / classes / ...以允许访问BOOT-INF / classes下的类。

例如,允许使用maven从包 uk.co.pervasive_intelligence.simulator.Component 中访问类,可以按以下方式完成

    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>

            <manifestEntries>
                <Class-Path>BOOT-NF/classes/uk/co/pervasive_intelligence/simulator/Component</Class-Path>
            </manifestEntries>
        </archive>
    </configuration>
</plugin> 

答案 2 :(得分:0)

如果使用SpringBoot和InteliJ Idea,则执行mvn clean package命令时,应使用maven pom中的packagename.jar.original,因为jar文件具有标准Java库的结构。

/META-INF
    /MANIFEST.MF
/uk
    /co
        /pervasive_intelligence
            /simulator
                /BaseComponent.class
                /SimulatorApplication.class
                /SimulatorException.class
....
相关问题