简体   繁体   中英

Dynamically load classes that need classpath reference in Java

I'm making a small console program which loads all the class files in a folder as "plugins", so that the program can be customizable by adding new classes.

Here is the problem: a plugin uses the SQL library to provide a simple querying system to a database. In order to include the jdbc driver it has the following code:

String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();

I compiled it adding the driver jar to the classpath:

javac -classpath ./libs/mysql-connector-java-5.1.40-bin.jar sqlquery.java

When I run the main jar which loads the plugin's .class file, even though I specify the driver jar in the program classpath, it throws a ClassNotFoundException when calling the com.mysql.jdbc.Driver class.

What can I do?

You should use either -jar or -cp to load the classes into the classpath, you can't combine the two .

Try this:

java -classpath "main.jar;./plugins/libs/mysql-connector-java-5.1.40-bin.jar" sqlquery.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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