Groovy类加载器不会加载Java类

时间:2014-09-14 12:06:08

标签: java groovy classloader

我有这个用.groovy文件写的groovy脚本:

import groovy.sql.Sql;
def doit() {
    Class.forName('oracle.jdbc.driver.OracleDriver'); // If i skip this line it throws SQLException no driver registered for URL
    def db = [url:'jdbc:oracle:thin:/@localhost:1555:AVDB', user:'sys as sysdba', password:'secret',driver:'oracle.jdbc.driver.OracleDriver'];
    def sql = Sql.newInstance(db.url, db.user, db.password, db.driver) ;
    sql.execute 'CREATE USER RandomUser identified by Secret123';
}

我通过以下方式从Java调用Groovy:

ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);

Class groovyClass = loader.parseClass(groovySource); // groovySource is a File object pointing to .groovy file
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] args = {};
groovyObject.invokeMethod("doit", args);

问题

oracle.jdbc.driver.OracleDriver 存在于Java的类路径中,但是groovy无法在行中找到它:Class.forName('oracle.jdbc.driver.OracleDriver');

抛出ClassNotFoundException。

2 个答案:

答案 0 :(得分:1)

在groovy方法之前尝试魔术线:

@groovy.transform.CompileStatic
def doit(){....}

答案 1 :(得分:1)

你应该简单地将java CL传递给你的groovy方法:

def doit( ClassLoader cl ) {
  cl.loadClass 'oracle.jdbc.driver.OracleDriver'
  ....
}

然后致电

ClassLoader parent = getClass().getClassLoader();
Object[] args = { parent };
groovyObject.invokeMethod("doit", args);