invokeMethod from Groovy with no parameters
I have some Java code that seemed to work fine:
/**
* Helper method
* 1. Specify args as Object[] for convenience
* 2. No error if method not implemented
* (GOAL: Groovy scripts as simple as possible)
*
* @param name
* @param args
* @return
*/
Object invokeGroovyScriptMethod(String name, Object[] args) {
Object result = null;
try {
result = groovyObject.invokeMethod(name, args);
} catch (exception) { // THIS HAS BEEN GROVIED...
if (exception instanceof MissingMethodException) {
if (log.isDebugEnabled()) {
log.debug("invokeGroovyScriptMethod: ", exception);
}
} else {
rethrow exception;
}
}
return result;
}
Object invokeGroovyScriptMethod(String name) {
return invokeGroovyScriptMethod(name, [ null ] as Object[]);
}
Object invokeGroovyScriptMethod(String name, Object arg0) {
return invokeGroovyScriptMethod(name, [ arg0 ] as Object[]);
}
Object invokeGroovyScriptMethod(String name, Object arg0, Object arg1) {
return invokeGroovyScriptMethod(name, [ arg0, arg1 ] as Object[]);
}
but I am having problems with the method:
Object invokeGroovyScriptMethod(String name) {
retur开发者_JAVA技巧n invokeGroovyScriptMethod(name, [ null ] as Object[]);
}
groovy.lang.MissingMethodException: No signature of method: MyClass.getDescription() is applicable for argument types: (null) values: [null]
Possible solutions: getDescription(), setDescription(java.lang.Object)
Any hints?
Thank you Misha
I had a quick go (getting rid of the log bit and replacing it with a println as I didn't have the logs set up in my tests), and I came up with this that doesn't require the overloaded versions of invokeGroovyScriptMethod:
Object invokeGroovyScriptMethod( String name, Object... args = null ) {
try {
args ? groovyObject."$name"( args.flatten() ) : groovyObject."$name"()
} catch( exception ) {
if( exception instanceof MissingMethodException ) {
println "invokeGroovyScriptMethod: $exception.message"
} else {
throw exception;
}
}
}
groovyObject = 'hi'
assert 'HI' == invokeGroovyScriptMethod( 'toUpperCase' )
assert 'i' == invokeGroovyScriptMethod( 'getAt', 1 )
assert '***hi' == invokeGroovyScriptMethod( 'padLeft', 5, '*' )
// Assert will pass (as we catch the exception, print the error and return null)
assert null == invokeGroovyScriptMethod( 'shouldFail' )
edit
Just read the question again, and you say this is a Java class? But then the catch seems to point to this being Groovy code...
I fear I may have sent you down the wrong path if this is Java...
精彩评论