简体   繁体   English

将参数从java传递到groovy

[英]pass parameters from java to groovy

I have a groovy script like:我有一个 groovy 脚本,如:

import groovy.sql.Sql

Object execute(def params = null) {

    def sql = new DBUtils().getConnection()

    println "sql params : " + params

    ...
}

And the java class will call this script like:并且 java 类将调用这个脚本,如:

Class scriptClass = new GroovyClassLoader().parseClass( new File(url) ) ;

Object scriptInstance = scriptClass.newInstance() ;

String param = {"test"};

Object obj = scriptClass.getDeclaredMethod("execute", new Class[] {})
    .invoke( scriptInstance, new Object[] {param}  ) ;

I've tried various format arguments but none of them work.我尝试了各种格式参数,但没有一个起作用。 The above sample will throw the java.lang.IllegalArgumentException: wrong number of arguments上面的示例会抛出java.lang.IllegalArgumentException: wrong number of arguments

Any thoughts?有什么想法吗? appreciated.赞赏。

You don't specify the arguments' type properly, it should be:您没有正确指定参数的类型,它应该是:

String param = "test";
Object obj = scriptClass.getDeclaredMethod("execute", new Class[]{Object.class})
    .invoke(scriptInstance, new Object[]{param});

Indeed, if you call getDeclaredMethod("execute", new Class[]{}) , you will get a method execute with no argument so it is not compatible with an invoke using an argument as you are trying to do.实际上,如果您调用getDeclaredMethod("execute", new Class[]{}) ,您将获得一个没有参数的方法execute ,因此它与您尝试使用参数的invoke不兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM