日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

protected修飾的構(gòu)造方法在不同包中的使用

作者:鄒鄒超人 更新時(shí)間: 2022-07-26 編程語言

今天在轉(zhuǎn)換json串的時(shí)候,看到了一種寫法

MessageVO<String> messageVo = JSON.parseObject(msgContent, new TypeReference<MessageVO<String>>() {});

在最后邊加了一對 ’ {} ’ ,剛開始對這個(gè)很迷惑,但是看了TypeReference的源碼之后明白了

protected TypeReference() {
        Type superClass = this.getClass().getGenericSuperclass();
        Type type = ((ParameterizedType)superClass).getActualTypeArguments()[0];
        Type cachedType = (Type)classTypeCache.get(type);
        if (cachedType == null) {
            classTypeCache.putIfAbsent(type, type);
            cachedType = (Type)classTypeCache.get(type);
        }

        this.type = cachedType;
    }

    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++];
            }

            if (argTypes[i] instanceof GenericArrayType) {
                argTypes[i] = TypeUtils.checkPrimitiveArray((GenericArrayType)argTypes[i]);
            }

            if (argTypes[i] instanceof ParameterizedType) {
                argTypes[i] = this.handlerParameterizedType((ParameterizedType)argTypes[i], actualTypeArguments, actualIndex);
            }
        }

        Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType);
        Type cachedType = (Type)classTypeCache.get(key);
        if (cachedType == null) {
            classTypeCache.putIfAbsent(key, key);
            cachedType = (Type)classTypeCache.get(key);
        }

        this.type = cachedType;
    }

我們可以看到他的構(gòu)造方法使用protect方法修飾,也就是只能在當(dāng)錢包中才能訪問,別的包就不可以了,但是我們可以使用創(chuàng)建一個(gè)子類的方法去使用TypeReference的構(gòu)造方法。

import com.alibaba.fastjson.TypeReference;

public class TypeTestChild<T> extends TypeReference<T> {
}

那么當(dāng)我們寫代碼時(shí),就可以使用子類的構(gòu)造方法去訪問父類的構(gòu)造方法;

Map<String, Object> objectMapTest = JSON.parseObject(responseStr, new TypeTestChild<Map<String, Object>>());

這也就是我們之前看到的

MessageVO<String> messageVo = JSON.parseObject(msgContent, new TypeReference<MessageVO<String>>() {});```

原文鏈接:https://blog.csdn.net/weixin_43790562/article/details/125984041

欄目分類
最近更新