2016-08-30 154 views
0

我想创建一个通用的REST API的方法,如:可以groovy支持可变参数和默认参数?

List<T> fetchResponse(HttpMethod requestType, Class<T> typeParam, String format = null, String urlSuffix, Object... params) { 
... 
} 

“格式化”将只存在时,我期望在响应日期和需要正确地解析他们。这些参数将始终是字符串。我担心的是,这会在运行时产生与哪些值对应哪些属性的歧义。这会工作吗?

回答

2

虽然支持这两者,但客户端编码器可能存在混淆。我写了一些模拟课程来说明。首先,如果我想省略format,指定urlSuffix,并提供2 params,我可能会尝试:

fetcher.fetchResponse(hm, String.class, "x", "y", "z") 

然而,观察断言:

class HttpMethod {} 

class Fetcher<T> { 
    def args = [:] 
    List<T> fetchResponse(HttpMethod requestType, 
          Class<T> typeParam, 
          String format = null, 
          String urlSuffix, 
          Object... params) { 
     args["requestType"] = requestType 
     args["typeParam"] = typeParam 
     args["format"] = format 
     args["urlSuffix"] = urlSuffix 
     args["params"] = params 
    } 
} 

def hm = new HttpMethod() 
def fetcher = new Fetcher<String>() 
fetcher.fetchResponse(hm, String.class, "x", "y", "z") 

assert hm == fetcher.args["requestType"] 
assert String.class == fetcher.args["typeParam"] 
assert "x" == fetcher.args["format"] 
assert "y" == fetcher.args["urlSuffix"] 
assert ["z"] == fetcher.args["params"] 

注意format"x"。如果一个人改变签名的为了(httpMethod, format = null, typeParam, urlSuffix, params),那么这可能是可以接受的:

fetcher.fetchResponse(hm, String.class, "x", "y", "z") 

assert hm == fetcher.args["requestType"] 
assert null == fetcher.args["format"] 
assert String.class == fetcher.args["typeParam"] 
assert "x" == fetcher.args["urlSuffix"] 
assert ["y", "z"] == fetcher.args["params"] 

一种替代方法是接受Map作为参数传递给该方法,然后使用named parameters

fetcher.fetchResponse(requestType: hm, urlSuffix: "x", typeParam: String.class, params: ["y", "z"]) 

(该选项与您的问题并不完全相关,但对客户可能更容易。)