search
HomeJavajavaTutorialHow to use TypeReference in Java

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 corresponding The three methods of ParameterizedType have the following values:

[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.Integer

getSuperclass:class java.util.AbstractMap
getGenericSuperclass:java.util.AbstractMap
K
V

getSuperclass: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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

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

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

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

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

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

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

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]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

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

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

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

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools