I am trying to run Java code at runtime through a JShell instance created using the JShell API . To demonstrate my problem, I am going to share my simple code.
With my current setup, I have a lib directory in which there is a Java Java driver: mysql-connector-java-5.1.35.jar.
Starting JShell with a command tool and adding the required module as:
jshell --module-path lib --add-modules mysql.connector.java
and then loading the mysql driver works for me:
jshell> Class.forName("com.mysql.jdbc.Driver").newInstance();
$1 ==> com.mysql.jdbc.Driver@42f93a98
I created a similar Java 9 module with module-info.java
like:
module example.loadmysql {
requires java.sql;
requires mysql.connector.java;
requires jdk.jshell;
}
src / example / loadmysql / Runner.java as:
package example.loadmysql;
import jdk.jshell.*;
import java.sql.*;
public class Runner {
public static void main(String[] args) throws Exception {
System.out.println(Class.forName("com.mysql.jdbc.Driver").newInstance());
JShell js = JShell.create();
String code = ""
+ "try {"
+ " Class.forName(\"com.mysql.jdbc.Driver\").newInstance();"
+ "} catch (Exception e) {"
+ " System.out.println(e.toString());"
+ "}";
js.eval(code);
}
}
After assembly / packaging:
java -p lib -m example.loadmysql
com.mysql.jdbc.Driver@6a4f787b
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
, example.loadmysql mysql, JShell . .
, JShell, JShell?
UPDATE. , :
String modulePath = System.getProperty("jdk.module.path");
js.eval("System.setProperty(\"jdk.module.path\", \""
+ modulePath + "\");");
. - .