Home > Java > javaTutorial > body text

How to use TypeReference in Java

WBOY
Release: 2023-04-24 23:07:05
forward
1872 people have browsed it

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]
Copy after login
{"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());
Copy after login

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;
}
Copy after login

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 对象,表示此类型是其成员之一的类型。
Copy after login

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
Copy after login

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();
}
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template