1

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?

1 Answer 1

4

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.

1
  • I appreciate the thorough explanation, I clearly misunderstood how javac handles jar files Sep 9, 2015 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.