我有一些似乎工作正常的Java代码:
/**
* 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[]);
}
但是我遇到了这个方法的问题:
Object invokeGroovyScriptMethod(String name) {
return 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)
任何提示?
谢谢 米莎
答案 0 :(得分:1)
我快速离开(摆脱日志位并用println替换它,因为我没有在我的测试中设置日志),我想出了这个不需要重载的版本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' )
修改
再次阅读问题,你说这是一个Java类吗?但后来这个问题似乎指出这是Groovy代码......
我担心如果这是Java,我可能会把你送错路径......