can a class in a jar use a class in a different jar

后端 未结 3 925
失恋的感觉
失恋的感觉 2021-01-24 09:15

I am new to java so not sure I fully understand jar files.

I want to put some common code in a library jar, which I then use from applications that are in different jars

相关标签:
3条回答
  • 2021-01-24 10:03

    If the Class-Path attribute of the manifest of the application jar file is

    mylibrary-0.0.1-SNAPSHOT.jar
    

    and the two jar files are in the same directory, then running

    java -jar myapp-0.0.1-SNAPSHOT.jar should work.
    

    You can also set the classpath explicitely, and set the main class explicitely, which is much easier, and doesn't rely on relative paths in the manifest.

    java -cp myapp-0.0.1-SNAPSHOT.jar:mylibrary-0.0.1-SNAPSHOT.jar org.myorg.myapp.Main
    

    You should not use the -classpath and the -jar options in the same command. It's one or the other.

    0 讨论(0)
  • 2021-01-24 10:04

    This should be marked as a duplicate of this question I just came across

    It is the exact problem and solution, which I could not find with all my previous searching until I knew exactly what I was searching for, i.e. Executable JAR ignores its own Class-Path attribute

    So not a java problem at all but a maven problem and the usual sparse maven documentation sheds no light on the problem at all. Unfortunately the sample config I copied included the setting, which by default is turned off. Final solution, don't use indexing with the maven plugin.

    0 讨论(0)
  • 2021-01-24 10:07

    Try some modification in the pom.xml

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>org.myorg.myapp.Main</mainClass>
                    <addClasspath>true</addClasspath>
                </manifest>
            </archive>
        </configuration>
    </plugin>
    

    And after this if you still have problems just unpack your myapp-0.0.1-SNAPSHOT.jar using any unzip tool. After unzipping it check the path of mylibrary-0.0.1-SNAPSHOT.jar in the MANIFEST file in META-INF folder.

    0 讨论(0)
提交回复
热议问题