日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Java的List和Json转换以及StringRedisTemplate往redis存泛型对象

發(fā)布時間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java的List和Json转换以及StringRedisTemplate往redis存泛型对象 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

List轉(zhuǎn)Json

List<User> user= new ArrayList();
String str = JSON.toJSONString(user);

Json 轉(zhuǎn)List方法一

List<User> user= JSON.parseArray(json,User.class); 

?

如果是泛型方法需要使用TypeReference

Json 轉(zhuǎn)List 方法二

String json = "[{}]"; 
List<user> user= JSON.parseObject(json,new TypeReference<List<User>>(){});

泛型T

Json 轉(zhuǎn)List方法三

List<T> students = JSON.parseObject(listCache,new TypeReference<List<T>>(){});

?

綜合例子:Springboot環(huán)境下利用StringRedisTemplate往redis存泛型對象

一開始要注入下StringRedisTemplate

@Autowired
private StringRedisTemplate redisTemplate;

?Redis獲取值不存在就從數(shù)據(jù)庫取出來json化存緩存,存在則直接反序列化json為List?

List<T> list;
String listCache=redisTemplate.opsForValue().get(key);
if(listCache!=null){list = JSON.parseObject(listCache,new TypeReference<List<T>>(){});
}
else {list = userService.getAllList();redisTemplate.opsForValue().set(key, JSON.toJSONString(list), 60 * 1, TimeUnit.SECONDS);
}

附錄:TypeReference源碼?

package com.alibaba.fastjson;import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.alibaba.fastjson.util.TypeUtils;/** * Represents a generic type {@code T}. Java doesn't yet provide a way to* represent generic types, so this class does. Forces clients to create a* subclass of this class which enables retrieval the type information even at* runtime.** <p>For example, to create a type literal for {@code List<String>}, you can* create an empty anonymous inner class:** <pre>* TypeReference&lt;List&lt;String&gt;&gt; list = new TypeReference&lt;List&lt;String&gt;&gt;() {};* </pre>* This syntax cannot be used to create type literals that have wildcard* parameters, such as {@code Class<?>} or {@code List<? extends CharSequence>}.*/
public class TypeReference<T> {static ConcurrentMap<Type, Type> classTypeCache= new ConcurrentHashMap<Type, Type>(16, 0.75f, 1);protected final Type type;/*** Constructs a new type literal. Derives represented class from type* parameter.** <p>Clients create an empty anonymous subclass. Doing so embeds the type* parameter in the anonymous class's type hierarchy so we can reconstitute it* at runtime despite erasure.*/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;}/*** @since 1.2.9* @param actualTypeArguments*/protected TypeReference(Type... actualTypeArguments){Class<?> thisClass = this.getClass();Type superClass = thisClass.getGenericSuperclass();ParameterizedType argType = (ParameterizedType) ((ParameterizedType) superClass).getActualTypeArguments()[0];Type rawType = argType.getRawType();Type[] argTypes = argType.getActualTypeArguments();int actualIndex = 0;for (int i = 0; i < argTypes.length; ++i) {if (argTypes[i] instanceof TypeVariable &&actualIndex < actualTypeArguments.length) {argTypes[i] = actualTypeArguments[actualIndex++];}// fix for openjdk and android envif (argTypes[i] instanceof GenericArrayType) {argTypes[i] = TypeUtils.checkPrimitiveArray((GenericArrayType) argTypes[i]);}// 如果有多層泛型且該泛型已經(jīng)注明實現(xiàn)的情況下,判斷該泛型下一層是否還有泛型if(argTypes[i] instanceof ParameterizedType) {argTypes[i] = handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex);}}Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType);Type cachedType = classTypeCache.get(key);if (cachedType == null) {classTypeCache.putIfAbsent(key, key);cachedType = classTypeCache.get(key);}type = cachedType;}private Type handlerParameterizedType(ParameterizedType type, Type[] actualTypeArguments, int actualIndex) {Class<?> thisClass = this.getClass();Type rawType = type.getRawType();Type[] argTypes = type.getActualTypeArguments();for(int i = 0; i < argTypes.length; ++i) {if (argTypes[i] instanceof TypeVariable && actualIndex < actualTypeArguments.length) {argTypes[i] = actualTypeArguments[actualIndex++];}// fix for openjdk and android envif (argTypes[i] instanceof GenericArrayType) {argTypes[i] = TypeUtils.checkPrimitiveArray((GenericArrayType) argTypes[i]);}// 如果有多層泛型且該泛型已經(jīng)注明實現(xiàn)的情況下,判斷該泛型下一層是否還有泛型if(argTypes[i] instanceof ParameterizedType) {return handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex);}}Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType);return key;}/*** Gets underlying {@code Type} instance.*/public Type getType() {return type;}public final static Type LIST_STRING = new TypeReference<List<String>>() {}.getType();
}

TypeReference的存在是因為java中子類可以獲取到父類泛型的真實類型。

其中核心的方法是:getActualTypeArguments,它可以得到父類的反省類型

ParameterizedType是一個記錄類型泛型的接口, 繼承自Type,一共三方法:

Type[] getActualTypeArguments(); //返回泛型類型數(shù)組
Type getRawType(); //返回原始類型Type
Type getOwnerType(); //返回 Type 對象,表示此類型是其成員之一的類型。
https://yq.aliyun.com/articles/609441

Map<String, Integer> intMap = new HashMap<>();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("getActualTypeArguments>>>"+t);}}

?

?

擴展閱讀Java如何獲得泛型類的真實類型:

package com.paopaoedu.springboot.demo;import com.paopaoedu.springboot.bean.User;import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;public class BaseDao<T>{private Class<T> clazz;// 使用反射技術(shù)得到T的真實類型public Class getRealType(){Class c=this.getClass();//getSuperclass()獲得該類的父類System.out.println("getSuperclass        >>>"+c.getSuperclass());//getGenericSuperclass()獲得帶有泛型的父類System.out.println("getGenericSuperclass >>>"+c.getGenericSuperclass());//Type是 Java 編程語言中所有類型的公共高級接口。它們包括原始類型、參數(shù)化類型、數(shù)組類型、類型變量和基本類型。Type type=c.getGenericSuperclass();System.out.println("Type                 >>>"+type);//ParameterizedType參數(shù)化類型,即泛型// 獲取當前new的對象的泛型的父類類型ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();// 獲取第一個類型參數(shù)的真實類型this.clazz = (Class<T>) pt.getActualTypeArguments()[0];c=(Class) pt.getActualTypeArguments()[0];System.out.println(c);return clazz;}}class userdemo extends BaseDao<User>{public static void main(String[] args) {userdemo classB = new userdemo();Class realType = classB.getRealType();System.out.println(realType.getName());}
}

?

總結(jié)

以上是生活随笔為你收集整理的Java的List和Json转换以及StringRedisTemplate往redis存泛型对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。