2010-08-16 108 views
1

我有一個似乎做工精細一些Java代碼:invokeMethod中不帶任何參數

/** 
* 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) 

任何提示?

謝謝 米莎

回答

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') 

編輯

只是再次讀取的問題,你說這是一個JAV一類?但隨後追趕似乎指向這個是Groovy代碼...

我擔心我可能已經給你發錯了路,如果這就是Java ...

+0

哇,這是真棒。我知道我的代碼有什麼問題btw Object invokeGroovyScriptMethod(String name){ return invokeGroovyScriptMethod(name,[null] as Object []); } 應該是 對象invokeGroovyScriptMethod(字符串名稱){ 返回invokeGroovyScriptMethod(姓名,[]爲Object []); } 米莎 – 2010-08-17 16:24:22

+1

換句話說[空]爲Object []應該是[]爲Object [] – 2010-08-17 16:24:46

+0

僅供參考,如果它的好,我張貼您的代碼段在這裏 http://groovy.329449.n5.nabble.com /invokeMethod-from-Groovy-with-no-parameters-td2637455.html#a2637455 – 2010-08-17 16:29:54

相關問題