I have a method that convert json string into a Map with generic value type:
public <T> Map<String, T> convert(String str) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(str, new TypeReference<Map<String, T>>() {});
}
The example usage:
Map<String, Foo> map = obj.convert(jsonString);
When run, I got error:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.example.Foo
Is there a solution for this?
@s101d1 Such usage can not be supported, unfortunately, since type variable T is only known to compiler and there is no real parameter passed during runtime. So T can only be known as java.lang.Object; anything caller uses will only result in a cast.
The solution is to pass actual Class<T> value along: this must be passed to know the type.
I also encountered this problem, how did you solve it?
Most helpful comment
@s101d1 Such usage can not be supported, unfortunately, since type variable
Tis only known to compiler and there is no real parameter passed during runtime. SoTcan only be known asjava.lang.Object; anything caller uses will only result in a cast.The solution is to pass actual
Class<T>value along: this must be passed to know the type.