简体   繁体   中英

Guava TypeToken for resolving raw type warnings

I am trying to solve Java raw-type warnings because of using a non-typed library. Eg

List dataAsList = response.getDataList();

I know that the list is of type

List<Map<String,Object>> 

But I don't know how to convert the untyped "response.getDataList()" to a typed version.

I read Guava TypeToken could be used for type-problems, but I am not sure how to use this and my attempts are not working.

If the List 's generic argument is a raw type, ie, it does not have generic arguments itself, please view my answer to a different question which uses a Guava solution.

Otherwise, you could do serialize/deserialize with Gson . This is probably relatively slow compared to other solutions, but is the cleanest to implement. Assuming that you are not doing this to many times per request it should not be any worse than making any I/O call such as a database request. The example below actually is an optimized modification of an example usage in the Gson API .

This example should work for most simple classes that do not need specialized serialization.

private final static Gson GSON = new Gson();

public static <T> T cast(Object object, TypeToken<T> token){
     String json = GSON.toJson(object);
     T result = GSON.fromJson(json, token.getType());
     return result;
}

Usage:

List<Map<String,String>> dataAsList = cast(
   response.getDataList(), new TypeToken<List<Map<String,String>>>(){});

Disclaimer:

In the exact situation you describe this solution will not work because the Maps value type is Object and Gson does not know which type you want to convert to. I am not sure if it will throw an exception or if it will just leave it as a JsonObject or some other type. I will try to research this more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM