简体   繁体   中英

Java/Jackson - how does TypeReference() actually work?

I'm parsing JSON strings sent from my WLAN speakers using Java/Jackson, whose format is unfortunately varying. While there's some static and not so important part of the response which is quite easy to parse, the really essential stuff may have many different structures, depending on the command sent to the speaker.

For that purpose, I think jackson's TypeReference() is best to map the current structure to key/value pairs and then see what we have. Problem is that I don't really understand how TypeReference works, and I don't want to blindly use "magic" functions where I have no clue what's actually happening. The reference states that sub classing is used, but the following syntax is not really clear to me, especially and foremost the empty curly brackets at the end:

TypeReference ref = new TypeReference<List<Integer>>() { };

Can someone explain to me how this class works? Many thanks in advance!

Type Reference / TypeToken / ParameterizedTypeReference

TypeReference is from Jackson , there's also Gson's TypeToken and Spring's ParameterizedTypeReference .

Why we need it?

The purpose is to capture the generic type and retain it at runtime , because generics only works at compile-time (type erasure), so at runtime, in your example, this List<Integer> has been erased.

Instantiate a direct subclass of an abstract class ie TypeReference

The ending class body {} is part of a class instance creation expression to create an anonymous class . The reference is JLS - Section # 15.9.1 .

15.9.1. Determining the Class being Instantiated If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:

If T denotes a class, then an anonymous direct subclass of the class named by T is declared. It is a compile-time error if the class denoted by T is a final class.

In either case, the body of the subclass is the ClassBody given in the class instance creation expression.

The class being instantiated is the anonymous subclass.

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