When using fastJson, TypeReference will be used in many scenarios for generic deserialization, for example:
void testTypeReference() { List<Integer> list = new ArrayList<>(); list.add(1); list.add(9); list.add(4); list.add(8); JSONObject jsonObj = new JSONObject(); jsonObj.put("a", list); System.out.println(jsonObj); List<String> list2 = jsonObj.getObject("a", new TypeReference<List<Integer>>(){}); System.out.println(list2); } //输出 1{"a":[1,9,4,8]} 2[1, 9, 4, 8]
{"msg":"","code":"0","data":[{"adjEq":"","details":[],"imr":"","isoEq":"","mgnRatio":"","mmr":"","notionalUsd":"","ordFroz":"","totalEq":"0","uTime":"1658332171773"}]} //拿code的值 String result1 = JSON.toJSONString(result); System.out.println("result1=="+result1); Result result2 = JSON.parseObject(result1, new TypeReference<Result>() {}); System.out.println(result2.getCode()); //拿data的值 Balance是data中数据的实体类 Result<List<Balance>> listResult = JSON.parseObject(result1, new TypeReference<Result<List<Balance>>>() {}); System.out.println("result2=="+listResult.getData());
Using TypeReference can clearly specify the deserialization type. For specific implementation logic, refer to the constructor of TypeReference
protected TypeReference(){ Type superClass = getClass().getGenericSuperclass(); Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; Type cachedType = classTypeCache.get(type); if (cachedType == null) { classTypeCache.putIfAbsent(type, type); cachedType = classTypeCache.get(type); } this.type = cachedType; }
Explanation:
The core method is: getActualTypeArguments, which can get the reflection of the parent class Type
ParameterizedType is a record type generic interface, inherited from Type, with a total of three methods:
Type[] getActualTypeArguments(); //返回泛型类型数组 Type getRawType(); //返回原始类型Type Type getOwnerType(); //返回 Type 对象,表示此类型是其成员之一的类型。
For example, Map
[class java.lang.String, class java.lang.String] interface java.util.Map null
Example:
package JsonLearn; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; public class TypeReferencBaseLearn { public static class IntMap extends HashMap<String, Integer> {} void test1() { IntMap intMap = new IntMap(); System.out.println(“getSuperclass:” + intMap.getClass().getSuperclass()); System.out.println(“getGenericSuperclass:” + intMap.getClass().getGenericSuperclass()); Type type = intMap.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType)type; for (Type t : p.getActualTypeArguments()) { System.out.println(t); } } } void test2() { Map<String, Integer> intMap = new HashMap<>(); System.out.println(“\ngetSuperclass:” + intMap.getClass().getSuperclass()); System.out.println(“getGenericSuperclass:” + intMap.getClass().getGenericSuperclass()); Type type = intMap.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType)type; for (Type t : p.getActualTypeArguments()) { System.out.println(t); } } } void test3() { Map<String, Integer> intMap = new HashMap<String, Integer>(){}; System.out.println(“\ngetSuperclass:” + intMap.getClass().getSuperclass()); System.out.println(“getGenericSuperclass:” + intMap.getClass().getGenericSuperclass()); Type type = intMap.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType)type; for (Type t : p.getActualTypeArguments()) { System.out.println(t); } } } public static void main(String[] args) { TypeReferencBaseLearn obj = new TypeReferencBaseLearn(); obj.test1(); obj.test2(); obj.test3(); } }
Output:
getSuperclass:class java.util.HashMap
getGenericSuperclass:java.util.HashMap
class java.lang.String
class java.lang.IntegergetSuperclass:class java.util.AbstractMap
getGenericSuperclass:java.util.AbstractMap
K
VgetSuperclass:class java.util. HashMap
getGenericSuperclass:java.util.HashMap
class java.lang.String
class java.lang.Integer
The above is the detailed content of How to use TypeReference in Java. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools