2

I have class with Class<?> field. I have a method, which has to cast string to object with help of Jackson.

private Class<?> myType = ...;
private String jsonRepresentationOfObject = ....;
ObjectMapper mapper = new ObjectMapper();

public <T> T get() {
   return mapper.readValue(jsonRepresentationOfObject, myType);
}

Is there any possibility to cast myType to T? Or it is impossible, because of type erasure?

Max
  • 1,403
  • 2
  • 14
  • 30
  • Why don't you use `Class`? – SilverNak Jul 27 '17 at 18:30
  • @SilverNak I have differents types, so I cannot use it. – Max Jul 27 '17 at 18:33
  • The signature ` T get()` says "I don't care what type `myType` is, I expect a `T`". What do you think casting `myType` will accomplish? – shmosel Jul 27 '17 at 18:37
  • 1
    @JFPicard How exactly is this question a duplicate of [Difference between super T> and extends T> in Java](https://stackoverflow.com/q/4343202/697630)? I don't find it event remotely related. – Edwin Dalorzo Jul 27 '17 at 19:43

2 Answers2

2

If you are absolutely sure that the result of readValue will be of type T you can do this:

public <T> T get() {
   return (T)mapper.readValue(jsonRepresentationOfObject, myType);
}

You will have to @SuppressWarnings for unchecked casts though.

In other languages (like Kotlin which can interop with Java) you can use reified generics but it is not present in Java because of type erasure.

If the result of readValue is not a T then you will get a ClassCastException so use this wisely.

Adam Arold
  • 26,256
  • 18
  • 92
  • 176
  • *If the result of readValue is not a `T` then you will get a `ClassCastException`*. Not necessarily. Hence the warning. – shmosel Jul 28 '17 at 19:57
-1

It's not possible, thanks to type erasure. This is why some library functions in Java have you pass in an instance of a class that isn't used for anything except doing a .getClass(). I'm actually writing very similar code right now and I ended up having a signature on the class of (the equivalent of) (T returnType) and then in the readValue call, I pass in returnType.getClass().

Don Hosek
  • 757
  • 4
  • 16