我想创建一个通用的REST api方法,如:
List<T> fetchResponse(HttpMethod requestType, Class<T> typeParam, String format = null, String urlSuffix, Object... params) {
...
}
&#39;格式&#39;只有当我在响应中期望日期并且需要正确解析它们时才会出现。参数永远也是字符串。我担心的是,这会产生关于哪些值对应于运行时哪些属性的含糊不清。这有用吗?
答案 0 :(得分: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"])
(此选项与您的问题并不完全相关,但对于客户来说可能更容易。)