1

How do I refer {} in java. Is it a new object or class or datatype or something else?

I am going through some code in json to object conversion. It uses com.fasterxml.jackson.core.type.TypeReference. I would like to understand what is {}. Because methods always accepts object. When I do new XXX() then creation of object is done. So what is the need of extra {}?

try {
  return objectMapper.readValue(dbData, new TypeReference<List<MyClass>>() {});
} catch (IOException e) {
  LOGGER.error("Exception while de-serializing", e);
  return Collections.emptyList();
}
Jan
  • 2,853
  • 2
  • 21
  • 26

2 Answers2

8

This is an anonymous class expression:

return objectMapper.readValue(dbData, new TypeReference<List<MyClass>>() {});
// -----------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It creates a new instance of an anonymous class extending TypeReference. The {} is an empty class body. As Paul Lemarchand says in a comment, it's useful here because TypeReference is an abstract class (otherwise, you could just use new TypeReference<List<MyClass>>() without the {}). The body can be blank because although TypeReference is abstract, it doesn't have any abstract members; if it had abstract members, you'd have to define them within the class body of the anonymous class.

More in the Java Anonymous Class Tutorial on Oracle's Java site.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

It creates an anonymous class extending TypeReference. Because TypeReference is abstract thus you cannot instantiate it directly.