Java javac compile with classpath

I was wondering if it's possible to include a jar in the classpath when compiling instead of executing. At the moment I am just checking to see if my PostgreSQL driver can be found

everything is in the same location for testing purposes so

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

DriverCheck.java contains

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow