最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?Bean轉(zhuǎn)Map的那些踩坑實戰(zhàn)

 更新時間:2022年07月10日 08:42:07   作者:明明如月學(xué)長  
項目中有時會遇到Map轉(zhuǎn)Bean,Bean轉(zhuǎn)Map的情況,下面這篇文章主要給大家介紹了關(guān)于Java?Bean轉(zhuǎn)Map那些踩坑的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、背景

有些業(yè)務(wù)場景下需要將 Java Bean 轉(zhuǎn)成 Map 再使用。

以為很簡單場景,但是坑很多。

二、那些坑

2.0 測試對象

import lombok.Data;
import java.util.Date;

@Data
public class MockObject extends  MockParent{
    private Integer aInteger;
    private Long aLong;
    private Double aDouble;
    private Date aDate;
}

父類

import lombok.Data;

@Data
public class MockParent {
    private Long parent;
}

2.1 JSON 反序列化了類型丟失

2.1.1 問題復(fù)現(xiàn)

將 Java Bean 轉(zhuǎn) Map 最常見的手段就是使用 JSON 框架,如 fastjson 、 gson、jackson 等。 但使用 JSON 將 Java Bean 轉(zhuǎn) Map 會導(dǎo)致部分?jǐn)?shù)據(jù)類型丟失。 如使用 fastjson ,當(dāng)屬性為 Long 類型但數(shù)字小于 Integer 最大值時,反序列成 Map 之后,將變?yōu)?Integer 類型。

maven 依賴:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.8</version>
        </dependency>

示例代碼:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.Date;
import java.util.Map;

public class JsonDemo {
    public static void main(String[] args) {
        MockObject mockObject = new MockObject();
        mockObject.setAInteger(1);
        mockObject.setALong(2L);
        mockObject.setADate(new Date());
        mockObject.setADouble(3.4D);
        mockObject.setParent(3L);
       String json = JSON.toJSONString(mockObject);
        Map<String,Object> map =  JSON.parseObject(json, new TypeReference<Map<String,Object>>(){});
        System.out.println(map);
    }
}

結(jié)果打?。?/p>

{"parent":3,"ADouble":3.4,"ALong":2,"AInteger":1,"ADate":1657299916477}

調(diào)試截圖:

通過 Java Visualizer 插件進行可視化查看:

2.2.2 問題描述

存在兩個問題 (1) 通過 fastjson 將 Java Bean 轉(zhuǎn)為 Map ,類型會發(fā)生轉(zhuǎn)變。 如 Long 變成 Integer ,Date 變成 Long, Double 變成 Decimal 類型等。 (2)在某些場景下,Map 的 key 并非和屬性名完全對應(yīng),像是通過 get set 方法“推斷”出來的屬性名。

2.2 BeanMap 轉(zhuǎn)換屬性名錯誤

2.2.1 commons-beanutils 的 BeanMap

maven 版本:

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

代碼示例:

import org.apache.commons.beanutils.BeanMap;
import third.fastjson.MockObject;
import java.util.Date;
public class BeanUtilsDemo {
    public static void main(String[] args) {
        MockObject mockObject = new MockObject();
        mockObject.setAInteger(1);
        mockObject.setALong(2L);
        mockObject.setADate(new Date());
        mockObject.setADouble(3.4D);
        mockObject.setParent(3L);
        BeanMap beanMap = new BeanMap(mockObject);
        System.out.println(beanMap);
    }
}

調(diào)試截圖:

存在和 cglib 一樣的問題,雖然類型沒問題但是屬性名還是不對。

原因分析:

   /**
     * Constructs a new <code>BeanMap</code> that operates on the
     * specified bean.  If the given bean is <code>null</code>, then
     * this map will be empty.
     *
     * @param bean  the bean for this map to operate on
     */
    public BeanMap(final Object bean) {
        this.bean = bean;
        initialise();
    }

關(guān)鍵代碼:

    private void initialise() {
        if(getBean() == null) {
            return;
        }

        final Class<? extends Object>  beanClass = getBean().getClass();
        try {
            //BeanInfo beanInfo = Introspector.getBeanInfo( bean, null );
            final BeanInfo beanInfo = Introspector.getBeanInfo( beanClass );
            final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if ( propertyDescriptors != null ) {
                for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    if ( propertyDescriptor != null ) {
                        final String name = propertyDescriptor.getName();
                        final Method readMethod = propertyDescriptor.getReadMethod();
                        final Method writeMethod = propertyDescriptor.getWriteMethod();
                        final Class<? extends Object> aType = propertyDescriptor.getPropertyType();

                        if ( readMethod != null ) {
                            readMethods.put( name, readMethod );
                        }
                        if ( writeMethod != null ) {
                            writeMethods.put( name, writeMethod );
                        }
                        types.put( name, aType );
                    }
                }
            }
        }
        catch ( final IntrospectionException e ) {
            logWarn(  e );
        }
    }

調(diào)試一下就會發(fā)現(xiàn),問題出在 BeanInfo 里面 PropertyDescriptor 的 name 不正確。

經(jīng)過分析會發(fā)現(xiàn) java.beans.Introspector#getTargetPropertyInfo 方法是字段解析的關(guān)鍵

對于無參的以 get 開頭的方法名從 index =3 處截取,如 getALong 截取后為 ALong, 如 getADouble 截取后為 ADouble。

然后去構(gòu)造 PropertyDescriptor:

/**
     * Creates <code>PropertyDescriptor</code> for the specified bean
     * with the specified name and methods to read/write the property value.
     *
     * @param bean   the type of the target bean
     * @param base   the base name of the property (the rest of the method name)
     * @param read   the method used for reading the property value
     * @param write  the method used for writing the property value
     * @exception IntrospectionException if an exception occurs during introspection
     *
     * @since 1.7
     */
    PropertyDescriptor(Class<?> bean, String base, Method read, Method write) throws IntrospectionException {
        if (bean == null) {
            throw new IntrospectionException("Target Bean class is null");
        }
        setClass0(bean);
        setName(Introspector.decapitalize(base));
        setReadMethod(read);
        setWriteMethod(write);
        this.baseName = base;
    }

底層使用 java.beans.Introspector#decapitalize 進行解析:

   /**
     * Utility method to take a string and convert it to normal Java variable
     * name capitalization.  This normally means converting the first
     * character from upper case to lower case, but in the (unusual) special
     * case when there is more than one character and both the first and
     * second characters are upper case, we leave it alone.
     * <p>
     * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays
     * as "URL".
     *
     * @param  name The string to be decapitalized.
     * @return  The decapitalized version of the string.
     */
    public static String decapitalize(String name) {
        if (name == null || name.length() == 0) {
            return name;
        }
        if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
                        Character.isUpperCase(name.charAt(0))){
            return name;
        }
        char chars[] = name.toCharArray();
        chars[0] = Character.toLowerCase(chars[0]);
        return new String(chars);
    }

從代碼中我們可以看出 (1) 當(dāng) name 的長度 > 1,且第一個字符和第二個字符都大寫時,直接返回參數(shù)作為PropertyDescriptor name。 (2) 否則將 name 轉(zhuǎn)為首字母小寫

這種處理本意是為了不讓屬性為類似 URL 這種縮略詞轉(zhuǎn)為 uRL ,結(jié)果“誤傷”了我們這種場景。

2.2.2 使用 cglib 的 BeanMap

cglib 依賴

<!-- https://mvnrepository.com/artifact/cglib/cglib -->
   <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>3.2.12</version>
   </dependency>

代碼示例:

import net.sf.cglib.beans.BeanMap;
import third.fastjson.MockObject;
import java.util.Date;
public class BeanMapDemo {
    public static void main(String[] args) {
        MockObject mockObject = new MockObject();
        mockObject.setAInteger(1);
        mockObject.setALong(2L);
        mockObject.setADate(new Date());
        mockObject.setADouble(3.4D);
        mockObject.setParent(3L);
        
        BeanMap beanMapp = BeanMap.create(mockObject);
        System.out.println(beanMapp);
    }
}

結(jié)果展示:

我們發(fā)現(xiàn)類型對了,但是屬性名依然不對。

關(guān)鍵代碼: net.sf.cglib.core.ReflectUtils#getBeanGetters 底層也會用到 java.beans.Introspector#decapitalize 所以屬性名存在一樣的問題就不足為奇了。

三、解決辦法

3.1 解決方案

解決方案有很多,本文提供一個基于 dubbo的解決方案。

maven 依賴:

<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo</artifactId>
    <version>3.0.9</version>
</dependency>

示例代碼:

import org.apache.dubbo.common.utils.PojoUtils;
import third.fastjson.MockObject;
import java.util.Date;
public class DubboPojoDemo {
    public static void main(String[] args) {
        MockObject mockObject = new MockObject();
        mockObject.setAInteger(1);
        mockObject.setALong(2L);
        mockObject.setADate(new Date());
        mockObject.setADouble(3.4D);
        mockObject.setParent(3L);

        Object generalize = PojoUtils.generalize(mockObject);

        System.out.println(generalize);
    }
}

調(diào)試效果:

Java Visualizer 效果:

3.2 原理解析

大家可以下載源碼來簡單研究下。 github.com/apache/dubb…

核心代碼: org.apache.dubbo.common.utils.PojoUtils#generalize(java.lang.Object)

public static Object generalize(Object pojo) {
     eturn generalize(pojo, new IdentityHashMap());
}

關(guān)鍵代碼:

// pojo 待轉(zhuǎn)換的對象
// history 緩存 Map,提高性能
 private static Object generalize(Object pojo, Map<Object, Object> history) {
        if (pojo == null) {
            return null;
        }

         // 枚舉直接返回枚舉名
        if (pojo instanceof Enum<?>) {
            return ((Enum<?>) pojo).name();
        }
        
        // 枚舉數(shù)組,返回枚舉名數(shù)組
        if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) {
            int len = Array.getLength(pojo);
            String[] values = new String[len];
            for (int i = 0; i < len; i++) {
                values[i] = ((Enum<?>) Array.get(pojo, i)).name();
            }
            return values;
        }

        // 基本類型返回 pojo 自身
        if (ReflectUtils.isPrimitives(pojo.getClass())) {
            return pojo;
        }

        // Class 返回 name
        if (pojo instanceof Class) {
            return ((Class) pojo).getName();
        }

        Object o = history.get(pojo);
        if (o != null) {
            return o;
        }
        history.put(pojo, pojo);

// 數(shù)組類型,遞歸
        if (pojo.getClass().isArray()) {
            int len = Array.getLength(pojo);
            Object[] dest = new Object[len];
            history.put(pojo, dest);
            for (int i = 0; i < len; i++) {
                Object obj = Array.get(pojo, i);
                dest[i] = generalize(obj, history);
            }
            return dest;
        }
// 集合類型遞歸
        if (pojo instanceof Collection<?>) {
            Collection<Object> src = (Collection<Object>) pojo;
            int len = src.size();
            Collection<Object> dest = (pojo instanceof List<?>) ? new ArrayList<Object>(len) : new HashSet<Object>(len);
            history.put(pojo, dest);
            for (Object obj : src) {
                dest.add(generalize(obj, history));
            }
            return dest;
        }
        // Map 類型,直接 對 key 和 value 處理
        if (pojo instanceof Map<?, ?>) {
            Map<Object, Object> src = (Map<Object, Object>) pojo;
            Map<Object, Object> dest = createMap(src);
            history.put(pojo, dest);
            for (Map.Entry<Object, Object> obj : src.entrySet()) {
                dest.put(generalize(obj.getKey(), history), generalize(obj.getValue(), history));
            }
            return dest;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        history.put(pojo, map);
        
        // 開啟生成 class 則寫入 pojo 的class
        if (GENERIC_WITH_CLZ) {
            map.put("class", pojo.getClass().getName());
        }
        
      // 處理 get 方法 
        for (Method method : pojo.getClass().getMethods()) {
            if (ReflectUtils.isBeanPropertyReadMethod(method)) {
                ReflectUtils.makeAccessible(method);
                try {
                    map.put(ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history));
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        }
        // 處理公有屬性
        for (Field field : pojo.getClass().getFields()) {
            if (ReflectUtils.isPublicInstanceField(field)) {
                try {
                    Object fieldValue = field.get(pojo);
                    // 對象已經(jīng)解析過,直接從緩存里讀提高性能
                    if (history.containsKey(pojo)) {
                        Object pojoGeneralizedValue = history.get(pojo);
                        // 已經(jīng)解析過該屬性則跳過(如公有屬性,且有 get 方法的情況)
                        if (pojoGeneralizedValue instanceof Map
                            && ((Map) pojoGeneralizedValue).containsKey(field.getName())) {
                            continue;
                        }
                    }
                    if (fieldValue != null) {
                        map.put(field.getName(), generalize(fieldValue, history));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        }
        return map;
    }

關(guān)鍵截圖

org.apache.dubbo.common.utils.ReflectUtils#getPropertyNameFromBeanReadMethod

public static String getPropertyNameFromBeanReadMethod(Method method) {
        if (isBeanPropertyReadMethod(method)) {
            // get 方法,則從 index =3 的字符小寫 + 后面的字符串
            if (method.getName().startsWith("get")) {
                return method.getName().substring(3, 4).toLowerCase()
                        + method.getName().substring(4);
            }
            // is 開頭方法, index =2 的字符小寫 + 后面的字符串
            if (method.getName().startsWith("is")) {
                return method.getName().substring(2, 3).toLowerCase()
                        + method.getName().substring(3);
            }
        }
        return null;
    }

因此, getALong 方法對應(yīng)的屬性名被解析為 aLong。

同時,這么處理也會存在問題。如當(dāng)屬性名叫 URL 時,轉(zhuǎn)為 Map 后 key 就會被解析成 uRL。

從這里看出,當(dāng)屬性名比較特殊時也很容易出問題,但 dubbo 這個工具類更符合我們的預(yù)期。 更多細(xì)節(jié),大家可以根據(jù) DEMO 自行調(diào)試學(xué)習(xí)。

如果想嚴(yán)格和屬性保持一致,可以使用反射獲取屬性名和屬性值,加緩存機制提升解析的效率。

四、總結(jié)

Java Bean 轉(zhuǎn) Map 的坑很多,最常見的就是類型丟失和屬性名解析錯誤的問題。 大家在使用 JSON 框架和 Java Bean 轉(zhuǎn) Map 的框架時要特別小心。 平時使用某些框架時,多寫一些 DEMO 進行驗證,多讀源碼,多調(diào)試,少趟坑。

到此這篇關(guān)于Java Bean轉(zhuǎn)Map的那些踩坑的文章就介紹到這了,更多相關(guān)Java Bean轉(zhuǎn)Map的坑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Boot整合web層實現(xiàn)過程詳解

    Spring Boot整合web層實現(xiàn)過程詳解

    這篇文章主要介紹了Spring Boot整合web層實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • Java實現(xiàn)多個sheet頁數(shù)據(jù)導(dǎo)出功能

    Java實現(xiàn)多個sheet頁數(shù)據(jù)導(dǎo)出功能

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)多個sheet頁數(shù)據(jù)導(dǎo)出功能的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • 詳解Java對象創(chuàng)建的過程及內(nèi)存布局

    詳解Java對象創(chuàng)建的過程及內(nèi)存布局

    今天給大家?guī)淼奈恼率荍ava對象創(chuàng)建的過程及內(nèi)存布局,文中有非常詳細(xì)的圖文示例及介紹,需要的朋友可以參考下
    2021-06-06
  • 深入理解Java定時調(diào)度(Timer)機制

    深入理解Java定時調(diào)度(Timer)機制

    這篇文章主要介紹了深入理解Java定時調(diào)度(Timer)機制,本節(jié)我們主要分析 Timer 的功能。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • SpringBoot如何獲取當(dāng)前操作用戶的id/信息

    SpringBoot如何獲取當(dāng)前操作用戶的id/信息

    在一般性的基設(shè)需求中,有需要獲取當(dāng)前用戶操作記錄的情況,也就是說我們需要記錄當(dāng)前用戶的信息,如:id、昵稱、賬號等信息,這篇文章主要介紹了SpringBoot獲取當(dāng)前操作用戶的id/信息,需要的朋友可以參考下
    2023-10-10
  • 一文徹底吃透SpringMVC中的轉(zhuǎn)發(fā)和重定向

    一文徹底吃透SpringMVC中的轉(zhuǎn)發(fā)和重定向

    大家應(yīng)該都知道springmvc本來就會把返回的字符串作為視圖名解析,然后轉(zhuǎn)發(fā)到對應(yīng)的視圖,這篇文章主要給大家介紹了關(guān)于SpringMVC中轉(zhuǎn)發(fā)和重定向的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-04-04
  • SpringBoot2.2.X用Freemarker出現(xiàn)404的解決

    SpringBoot2.2.X用Freemarker出現(xiàn)404的解決

    這篇文章主要介紹了SpringBoot2.2.X用Freemarker出現(xiàn)404的解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • IDEA的默認(rèn)快捷鍵設(shè)置與Eclipse的常用快捷鍵的設(shè)置方法

    IDEA的默認(rèn)快捷鍵設(shè)置與Eclipse的常用快捷鍵的設(shè)置方法

    這篇文章主要介紹了IDEA的默認(rèn)快捷鍵設(shè)置與Eclipse的常用快捷鍵的設(shè)置方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • Java實現(xiàn)寵物商店管理

    Java實現(xiàn)寵物商店管理

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)寵物商店管理,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-10-10
  • 基于javascript實現(xiàn)獲取最短路徑算法代碼實例

    基于javascript實現(xiàn)獲取最短路徑算法代碼實例

    這篇文章主要介紹了基于javascript實現(xiàn)獲取最短路徑算法代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02

最新評論

蒙阴县| 卢湾区| 景洪市| 孝义市| 三穗县| 金阳县| 隆回县| 汉源县| 三亚市| 家居| 吉木乃县| 五寨县| 静宁县| 额济纳旗| 朔州市| 麟游县| 北辰区| 同心县| 台南市| 县级市| 上虞市| 南开区| 三亚市| 突泉县| 岐山县| 昌图县| 德格县| 巴林左旗| 花垣县| 离岛区| 宁化县| 岳池县| 清徐县| 东乡县| 庆城县| 大冶市| 双鸭山市| 洮南市| 永城市| 溧水县| 建始县|