1

使用 JDK1.6.0_16,我有一个简单的程序,我试图让 beanshell 2.0b4 动态加载 .jar(正如文档所暗示的那样),但我没有运气。文档说,如果我使用 beanshells 的 getClass() 方法,那么它将加载以前由“addClassPath()”方法加载的 jar。它不工作。我需要这方面的帮助...

//debug();
addClassPath("mysql-connector-java-5.1.15.jar"); 
import com.mysql.jdbc.Driver; 
import java.sql.Connection;  
import java.sql.DriverManager; 
import java.util.Arrays;

System.out.println("MySQL Connect Example.");
System.out.println("Classpath: " + Arrays.toString( getClassPath() ) + "\n");

Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "password";
try {
  Class driverClass = getClass( driver );
  if(driverClass != null) {
    Driver driver = driverClass.newInstance();
    if(driver != null) {
      DriverManager.registerDriver(driver);
    }
  }
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
} catch (Exception e) {
  e.printStackTrace();
}

我遇到的这个问题强烈表明(beanshell 的)getClass() 方法无法看到它自己动态更改的类路径。

注意:此代码仅在我将 mysql.jar 文件放入 jre/lib/ext 目录时才有效(这是旧版 jre 类加载器可以加载它的位置;不是 beanshell 类加载器)

4

1 回答 1

1

this is probably not a beanshell thing, jdbc has issues loading drivers across classloaders (check out the class javadoc for ClassLoader, and see hacks like this).

于 2011-08-19T03:05:11.667 回答