简体   繁体   English

Java Javac使用类路径进行编译

[英]Java javac compile with classpath

I was wondering if it's possible to include a jar in the classpath when compiling instead of executing. 我想知道在编译而不是执行时是否可以在类路径中包含jar。 At the moment I am just checking to see if my PostgreSQL driver can be found 目前,我只是在检查是否可以找到我的PostgreSQL驱动程序

everything is in the same location for testing purposes so 一切都在同一位置以进行测试,因此

program/
    DriverCheck.java
    DriverCheck.class
    postgresql-longassname.jar

DriverCheck.java contains 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);
        }

    }

}

If I compile and execute this as normal 如果我正常编译并执行

# javac DriverCheck.java

# java -cp ".:./postgresql-longassname.jar" DriverCheck

It works as I get the output 当我得到输出时它起作用

Driver Found

However if I try to compile and execute in this manner 但是,如果我尝试以这种方式编译和执行

# javac -cp ".:./postgresql-longassname.jar" DriverCheck.java

# java DriverCheck

It does not work as I get the output 当我得到输出时它不起作用

Driver Not Found

Why is this and is there a way for me to use the second method for including jars? 为什么会这样,有没有办法让我使用第二种方法来添加罐子?

Why is this and is there a way for me to use the second method for including jars? 为什么会这样,有没有办法让我使用第二种方法来添加罐子?

It's because specifying the classpath for compilation just tells the compiler where to find types. 这是因为指定要编译的类路径只会告诉编译器在哪里可以找到类型。 The compiler doesn't copy those types into its output - so if you want the same resources available when you execute, you need to specify the classpath at execution time. 编译器不会这些类型复制到其输出中-因此,如果您希望在执行时使用相同的资源,则需要在执行时指定类路径。

In this case the compiler doesn't need the extra jar file at all - nothing in your source code refers to it... but you do need it at execution time... which is why your original approach works and your second approach doesn't. 在这种情况下,编译器根本不需要多余的jar文件-您的代码中没有内容引用它...但是您在执行时确实需要它...这就是为什么您的原始方法可行而第二种方法却没有的原因没错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM