我创建了一个Java文件,然后将其转换为jar,现在我想在另一个Java类中使用它,如何导入该jar以及如何编译和执行。
Given a "library" class pkg/LibClass.java
:
package pkg;
public class LibClass {
public static void sayHello() {
System.out.println("Hello world");
}
}
Compile and create a jar file:
$ javac pkg/LibClass.java
$ jar cvf lib.jar pkg/LibClass.class
added manifest
adding: pkg/LibClass.class(in = 404) (out= 284)(deflated 29%)
(creates a lib.jar
in the current directory)
Create an application that uses the library:
import pkg.LibClass;
public class MainClass {
public static void main(String[] args) {
LibClass.sayHello();
}
}
Compile and run the application using lib.jar
:
$ javac -cp lib.jar MainClass.java
$ java -cp lib.jar:. MainClass
当另一个Java文件正在被编译/执行时,您需要在编译时和运行时使该jar文件在classpath中可用。
Set the jar in your class path or pass as an argument and compile or execute -
Compile - javac -classpath your.jar other.java
Execute - java -classpath your.jar other
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.