[英]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. 这是问题所在:插件使用SQL库为数据库提供简单的查询系统。 In order to include the jdbc driver it has the following code: 为了包括jdbc驱动程序,它具有以下代码:
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
I compiled it adding the driver jar to the classpath: 我编译了它,将驱动程序jar添加到类路径中:
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. 当我运行加载插件的.class文件的主jar时,即使我在程序类路径中指定了驱动jar,它在调用com.mysql.jdbc.Driver
类时com.mysql.jdbc.Driver
引发ClassNotFoundException
。
What can I do? 我能做什么?
You should use either -jar
or -cp
to load the classes into the classpath, you can't combine the two . 您应该使用-jar
或-cp
将类加载到类路径中, 但不能将两者结合使用 。
Try this: 尝试这个:
java -classpath "main.jar;./plugins/libs/mysql-connector-java-5.1.40-bin.jar" sqlquery.java java -classpath“ main.jar; ./ plugins / libs / mysql-connector-java-5.1.40-bin.jar” sqlquery.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.