Dan*_*ans 0 java groovy dynamic
昨天我开始使用 Groovy,我发现了动态方法调用功能。这是一个很好的函数,可以根据方法名称动态调用方法。这对我来说很好用。现在我们想根据它们的名称和不同的参数来调用这些方法。例如我有两种方法:
def changeResponseWithParametersAandB(def response, String a, String b) {
response.result = args[0];
return response;
}
def changeResponseWithParameterA(def response, String a) {
response.result = args[0];
return response;
}
Run Code Online (Sandbox Code Playgroud)
我将遍历包含方法名称的列表,例如:
for (int i = 0; i < methods.size(); i++) {
DynamicMethods dynamicMethod = methods.get(i);
methodName = dynamicMethod.getMethodName();
changeFieldValues."$methodName"(response, <HOW_SHOULD_I_DO_THIS_PART>);
}
Run Code Online (Sandbox Code Playgroud)
唯一的问题是这不适用于这两种方法之一。我应该使用第一种方法 2 参数和第二种方法 3 参数。有没有办法在 groovy 中解决这个问题?或者我应该只使用地图/数组或类似的东西?
谢谢你的回答!
像下面这样的东西就足够了吗?您可以使用一种方法,第二个参数是可选的,而不是两种方法。我试图通过地图和列表来模拟实现。如果您需要更多说明,请大声说出来。
def changeResponseWithParametersAandB(def response, String a, String b = null) {
response.result = [first: a, second: b]
return response
}
def methods = [ 'changeResponseWithParametersAandB' ]
def response = [:]
def args = [ [ 'string1' ], [ 'string1', 'string2' ] ]
args.each { arg ->
methods.each { method ->
def result = "$method"( response, *arg )
assert arg.size() == 1 ?
result == [ result : [ first:'string1', second:null ] ] :
result == [ result : [ first:'string1', second:'string2' ] ]
}
}
return "Done testing"
Run Code Online (Sandbox Code Playgroud)