Search code examples
javascriptingjdbcbeanshell

JDBC connection with Beanshell


Other similar questions on StackOverflow didn't answer my question in this area. I have this script that doesn't work, and I am wondering how to get it to work:

// beanshell script script.bsh
import com.mysql.jdbc.Driver; 
import java.sql.Connection;  
name="com.mysql.jdbc.Driver"; 
c = getClass( name ); 
c = BshClassManager.classForName( name );  // equivalent 

And the error I get is:

// Debug: getResolvedMethod cache MISS: class bsh.BshClassManager - classForName
// Debug: Searching for method: classForName( java.lang.String ) in 'bsh.BshClassManager'
// Debug: Looking for most specific method: classForName
bsh.UtilEvalError: Cannot reach instance method: classForName( java.lang.String ) from static context: bsh.BshClassManager
        at bsh.Reflect.checkFoundStaticMethod(Unknown Source)
        at bsh.Reflect.resolveJavaMethod(Unknown Source)
        at bsh.Reflect.resolveExpectedJavaMethod(Unknown Source)
        at bsh.Reflect.invokeStaticMethod(Unknown Source)
        at bsh.Name.invokeMethod(Unknown Source)
        at bsh.BSHMethodInvocation.eval(Unknown Source)
        at bsh.BSHPrimaryExpression.eval(Unknown Source)
        at bsh.BSHPrimaryExpression.eval(Unknown Source)
        at bsh.BSHAssignment.eval(Unknown Source)
        at bsh.Interpreter.eval(Unknown Source)
        at bsh.Interpreter.source(Unknown Source)
        at bsh.Interpreter.main(Unknown Source)

The documentation says it should exist.


Solution

  • According to the http://beanshell.org/manual/classpath.html#Loading_Classes_Explicitly documentation you're free to choose either getClass( name ) or BshClassManager.classForName( name ) to load the driver. Note also the // equivalent comment.

    Perhaps the documentation just gave a wrong example of how to use the BshClassManager properly. But as it's just an "equivalent" you could remove that altogether. The getClass() should work just fine.