Java javac 使用类路径编译
Java javac compile with classpath
我想知道是否可以在编译而不是执行时在类路径中包含一个 jar。目前我只是检查是否可以找到我的 PostgreSQL 驱动程序
出于测试目的,一切都在同一位置,所以
program/
DriverCheck.java
DriverCheck.class
postgresql-longassname.jar
DriverCheck.java 包含
public class DriverCheck {
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
System.out.println(Driver Found);
} catch(Exception log) {
System.out.println(Driver Not Found);
}
}
}
如果我正常编译和执行它
# javac DriverCheck.java
# java -cp ".:./postgresql-longassname.jar" DriverCheck
它在我得到输出时工作
Driver Found
但是如果我尝试以这种方式编译和执行
# javac -cp ".:./postgresql-longassname.jar" DriverCheck.java
# java DriverCheck
当我得到输出时它不起作用
Driver Not Found
为什么会这样,有没有办法让我使用第二种方法来包含 jars?
Why is this and is there a way for me to use the second method for including jars?
这是因为指定编译的类路径只是告诉编译器在哪里可以找到类型。编译器不会将这些类型复制到它的输出中——所以如果你想在执行时使用相同的资源,你需要在执行时指定类路径。
在这种情况下,编译器根本不需要额外的 jar 文件 - source 代码中没有任何内容引用它......但你 在执行时需要它...这就是为什么您的原始方法有效而第二种方法无效的原因。
我想知道是否可以在编译而不是执行时在类路径中包含一个 jar。目前我只是检查是否可以找到我的 PostgreSQL 驱动程序
出于测试目的,一切都在同一位置,所以
program/
DriverCheck.java
DriverCheck.class
postgresql-longassname.jar
DriverCheck.java 包含
public class DriverCheck {
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
System.out.println(Driver Found);
} catch(Exception log) {
System.out.println(Driver Not Found);
}
}
}
如果我正常编译和执行它
# javac DriverCheck.java
# java -cp ".:./postgresql-longassname.jar" DriverCheck
它在我得到输出时工作
Driver Found
但是如果我尝试以这种方式编译和执行
# javac -cp ".:./postgresql-longassname.jar" DriverCheck.java
# java DriverCheck
当我得到输出时它不起作用
Driver Not Found
为什么会这样,有没有办法让我使用第二种方法来包含 jars?
Why is this and is there a way for me to use the second method for including jars?
这是因为指定编译的类路径只是告诉编译器在哪里可以找到类型。编译器不会将这些类型复制到它的输出中——所以如果你想在执行时使用相同的资源,你需要在执行时指定类路径。
在这种情况下,编译器根本不需要额外的 jar 文件 - source 代码中没有任何内容引用它......但你 在执行时需要它...这就是为什么您的原始方法有效而第二种方法无效的原因。