Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当泛型类型信息不可用时,如何避免编译器警告?_Java_Generics_Reflection_Generic Collections - Fatal编程技术网

Java 当泛型类型信息不可用时,如何避免编译器警告?

Java 当泛型类型信息不可用时,如何避免编译器警告?,java,generics,reflection,generic-collections,Java,Generics,Reflection,Generic Collections,我正在使用Spring的RestTemplate对RESTWeb服务进行调用。其中一个调用是返回特定类型的对象列表。restemplate方法要求提供一个类参数来指示预期的返回类型 // restTemplate is type org.springframework.web.client.RestTemplate URI restServiceURI = new URI("http://example.com/foo") restTemplate.getForObject(restServic

我正在使用Spring的
RestTemplate
对RESTWeb服务进行调用。其中一个调用是返回特定类型的对象列表。
restemplate
方法要求提供一个类参数来指示预期的返回类型

// restTemplate is type org.springframework.web.client.RestTemplate
URI restServiceURI = new URI("http://example.com/foo")
restTemplate.getForObject(restServiceURI, List<Foo>.class);
//restTemplate的类型为org.springframework.web.client.restTemplate
URI restServiceURI=新URI(“http://example.com/foo")
getForObject(restServiceURI,List.class);
很明显,这是不可编译的。如果提供这样的类型参数,则无法获得静态
.class
属性。当我删除类型参数时,代码会编译,但会生成
rawtypes
编译器警告


我的问题很简单。我是否一直在抑制编译器警告,或者是否有更干净的方法来为此编写代码?

但是RestTemplate如何知道将列表元素转换为类
Foo
的实例?你试过运行代码吗?它是否按预期工作

我能想到的解决这个问题的一种方法是使用数组作为输入类型。例如

restTemplate.getForObject(restServiceURI, Foo[].class);
但我不知道这是否得到支持。如果您真的需要对更复杂的数据类型进行反序列化,那么您应该考虑使用杰克逊或GSON。 使用Jackson,您可以使用该类轻松地反序列化来自大多数源的数据

String input = ...;
ObjectMapper mapper = new ObjectMapper();
List<Foo> list = mapper.readValue(input, new TypeReference<List<Foo>>(){});
字符串输入=。。。;
ObjectMapper mapper=新的ObjectMapper();
List List=mapper.readValue(input,newtypereference(){});

上述方法之所以有效,是因为您有意创建了一个扩展TypeReference的匿名类,该类将在运行时记住其泛型类型,因此它可以帮助对象映射器创建Foo的列表

Jackson在类路径上,Spring3.x会自动使用它对这些流进行整理/解整理。我希望利用这一优势,但似乎我需要在一个较低的层次上这样做。我只是感到惊讶的是,Spring并没有像处理其他模板类那样提供一种简单的方法来处理集合返回。我没有使用RestTemplate.getForObject(),而是使用RestTemplate.execute()并提供自己的ResponseExtractor。这让我通过了概念验证,但我认为有一种更聪明的方法来确定服务器的响应类型。现在我假设使用JSON,但我需要在某个时候支持XML。谢谢你的指导!