Mik*_*key 5 java generics reflection generic-collections
我正在使用Spring RestTemplate
来对REST Web服务进行调用.其中一个调用是返回某种类型的对象列表.这些RestTemplate
方法要求提供类参数以指示预期的返回类型.
// restTemplate is type org.springframework.web.client.RestTemplate
URI restServiceURI = new URI("http://example.com/foo")
restTemplate.getForObject(restServiceURI, List<Foo>.class);
Run Code Online (Sandbox Code Playgroud)
显然,这不编译..class
当您提供类似的类型参数时,您无法获得静态属性.我删除type参数时会编译代码,但会生成rawtypes
编译器警告.
我的问题很简单.我是坚持抑制编译器警告还是有更简洁的方法来代码?
但是 RestTemplate 如何知道将列表元素转换为 class 的实例Foo
?您是否尝试过运行代码,它是否按预期工作?
我能想到的解决这个问题的一种方法是使用数组作为输入类型。例如。
restTemplate.getForObject(restServiceURI, Foo[].class);
Run Code Online (Sandbox Code Playgroud)
但不知道是否支持。如果您确实需要反序列化更复杂的数据类型,那么您应该考虑使用 Jackson 或 Gson。
借助 Jackson,您可以使用ObjectMapper类轻松反序列化大多数来源的数据。
String input = ...;
ObjectMapper mapper = new ObjectMapper();
List<Foo> list = mapper.readValue(input, new TypeReference<List<Foo>>(){});
Run Code Online (Sandbox Code Playgroud)
上面的方法之所以有效,是因为您有意创建一个扩展 TypeReference 的匿名类,该类将在运行时记住其泛型类型,因此它可以帮助对象映射器创建 Foo 列表。以获得更全面的解释。
归档时间: |
|
查看次数: |
1887 次 |
最近记录: |