Run a JAR file from the command line and specify classpath

后端 未结 5 1087
耶瑟儿~
耶瑟儿~ 2020-11-22 10:44

I\'ve compiled a JAR file and specified the Main-Class in the manifest (I used the Eclipse Export function). My dependencies are all in a directory labeled li

相关标签:
5条回答
  • 2020-11-22 11:02

    Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

    Main-Class: com.test.App
    Class-Path: lib/one.jar lib/two.jar
    

    Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

    Then execute it with

    java -jar MyJar.jar
    
    0 讨论(0)
  • 2020-11-22 11:07

    Run a jar file and specify a class path like this:

    java -cp <jar_name.jar:libs/*> com.test.App
    

    jar_name.jar is the full name of the JAR you want to execute

    libs/* is a path to your dependency JARs

    com.test.App is the fully qualified name of the class from the JAR that has the main(String[]) method

    The jar and dependent jar should have execute permissions.

    0 讨论(0)
  • 2020-11-22 11:10

    You can do these in unix shell:

    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
    

    You can do these in windows powershell:

    java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main
    
    0 讨论(0)
  • 2020-11-22 11:26

    When you specify -jar then the -cp parameter will be ignored.

    From the documentation:

    When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

    You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

    You have two options:

    1. include all jar files from the lib directory into the manifest (you can use relative paths there)
    2. Specify everything (including your jar) on the commandline using -cp:
      java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
    0 讨论(0)
  • 2020-11-22 11:26

    You can do a Runtime.getRuntime.exec(command) to relaunch the jar including classpath with args.

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