将类添加到 JAR 文件的类路径中
原文: https://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
您可能需要从 JAR 文件中引用其他 JAR 文件中的类。
例如,在典型情况下,applet 捆绑在 JAR 文件中,该文件的清单引用不同的 JAR 文件(或几个不同的 JAR 文件)作为该 applet 的实用程序。
您可以指定要包含在 applet 或应用程序清单文件的Class-Path
标头字段中的类。 Class-Path
标头采用以下形式:
Class-Path: jar1-name jar2-name directory-name/jar3-name
通过使用清单中的Class-Path
标头,可以避免在调用 Java 来运行应用程序时指定长- 类路径
标志。
Note: The Class-Path
header points to classes or JAR files on the local network, not JAR files within the JAR file or classes accessible over Internet protocols. To load classes in JAR files within a JAR file into the class path, you must write custom code to load those classes. For example, if MyJar.jar
contains another JAR file called MyUtils.jar
, you cannot use the Class-Path
header in MyJar.jar's
manifest to load classes in MyUtils.jar
into the class path.
一个例子
我们希望将MyUtils.jar
中的类加载到类路径中,以便在MyJar.jar
中使用。这两个 JAR 文件位于同一目录中。
我们首先创建一个名为Manifest.txt
的文本文件,其中包含以下内容:
Class-Path: MyUtils.jar
Warning: The text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.
然后,我们通过输入以下命令创建名为MyJar.jar
的 JAR 文件:
jar cfm MyJar.jar Manifest.txt MyPackage/*.class
这将创建一个带有以下内容的清单的 JAR 文件:
Manifest-Version: 1.0
Class-Path: MyUtils.jar
Created-By: 1.7.0_06 (Oracle Corporation)
MyJtil.jar
中的类现在在运行MyJar.jar
时被加载到类路径中。