0

Having problem with casting in Java recently I have used TypeReference object of Jackson. The situation looked liked this:

List<myObject> listOfObjects = new ArrayList<myObject>();

listOfObjects = mapper.readValue(connection.getInputStream(), new ArrayList.class);

was throwing an exception that LinkedHashMap could not be cast into myObject. I understand now what was wrong with it after some helpful person on SO told me to use TypeReference. I replace second line with:

listOfObjects = mapper.readValue(connection.getInputStream(), new TypeReference<List<myObject>>(){});

and there is just one thing that I cannot (still...) understand here: what is the inner class for here ({})? I obviously don't know all use cases of inner classes so I could use a bit of explanation here. Thank you.

Averroes
  • 4,168
  • 6
  • 50
  • 63
Lucas
  • 3,181
  • 4
  • 26
  • 45
  • possible duplicate of [Does Jackson TypeReference work when extended?](http://stackoverflow.com/questions/19283606/does-jackson-typereference-work-when-extended) – Sotirios Delimanolis Mar 17 '14 at 16:10

1 Answers1

1

Java has a thing called type erasure. That means, once compiled, your

List<myObject> listOfObjects = new ArrayList<myObject>();

becomes

List listOfObjects = new ArrayList();

Therefore, once running your program Jackson cannot tell that you are expecting back a List of myObjects. Instead it returns a list of LinkedHashMaps. By creating an inner class extending TypeReference you are forcing Java to retain the fact that you are expecting a list of type myObject.

See here for the explanation from the Authors: http://fasterxml.github.io/jackson-core/javadoc/2.0.4/com/fasterxml/jackson/core/type/TypeReference.html

ced-b
  • 3,957
  • 1
  • 27
  • 39
  • Good explanation, thanks. I have found what you linked for a couple of minutes ago, but after posting the question, therefore even though I already knew the answer you're effort will be rewarded. And I really should start trying harder before posting questions, because it's not the first time :( Thanks! – Lucas Mar 17 '14 at 16:11
  • @fge I just took the first that came up in Google. Fixed that. Didn't make much of a difference. – ced-b Mar 17 '14 at 16:18