Search code examples
javamysqljarclassnotfoundexception

MySQL driver class not found, even when included in classpath


I have the following code:

mypackage\Launcher.java:

package mypackage;

import mypackage.MainClass;

public class Launcher
{
    public static void main(String[] args)
    {
        new MainClass(args);
    }
}

mypackage\MainClass.java:

package mypackage;

import java.sql.*;
import com.mysql.jdbc.Driver;

public class MainClass
{
    public MainClass(String[] args)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        }
        catch (Exception ex)
        {
            System.err.println("Error: unable to load sql driver class!");
            ex.printStackTrace(System.err);
            System.exit(1);
        }

        System.out.println("We got here... How???");
    }
}

The code compiles with no complaints using

javac -cp src;bin;lib\mysql-connector-java-5.1.38-bin.jar -sourcepath src -d bin src\mypackage\Launcher.java
jar cfe myjar.jar mypackage.Launcher .

but when running

java -cp .\mysql-connector-java-5.1.38-bin.jar -jar myjar.jar

I get the following error:

Error: unable to load sql driver class!
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at mypackage.MainClass.<init>(MainClass.java:10)
        at mypackage.Launcher.main(Launcher.java:9)

I don't understand what I am missing here, and I have spent over 6 hours attempting to debug and searching for answers, but I have not found anything that has helped (pretty much everything I've found says "include the jarfile containing the class on the classpath – but I've very clearly done just that).

What's going on?


Solution

  • -jar option

    ... When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

    The quickest way for you to launch it is to drop the -jar option, add your jar to the -cp list and use mypackage.MainClass as the last CLI argument.
    (just in case you are not aware) But only after you implement the public static void main(String[] args) method inside that class (no, the fact your class has a constructor doesn't matter)

    The way to maintain the -jar launching style is to enumerate all you dependency jar files into the Class-Path entry of the manifest.mf file of your main jar (the one also containing the Main-Class entry pointing to your launcher).
    Just be careful about the locations you expect your dependencies relative to the location of your launcher jar.