Java为实体类动态添加属性的方法详解

本文详细介绍在Java中使用CGLIB和CommonsBeanUtils库为已有实体类动态添加字段的方法,同时创建新对象并保持原对象结构不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java为实体类动态添加属性的方法详解

 更新时间:2022年06月01日 14:09:21   作者:执拗的小豆芽  

这篇文章主要介绍了Java如何给已有实体类动态的添加字段并返回新的实体对象且不影响原来的实体对象结构。文中的方法讲解详细,需要的可以参考一下

目录

可以给已有实体类动态的添加字段并返回新的实体对象,不影响原来的实体对象结构。

添加依赖

1

2

3

4

5

6

7

8

9

10

11

<dependency>

    <groupId>cglib</groupId>

    <artifactId>cglib</artifactId>

    <version>2.2.2</version>

</dependency>

<dependency>

    <groupId>commons-beanutils</groupId>

    <artifactId>commons-beanutils</artifactId>

    <version>1.9.4</version>

</dependency>

代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

import com.google.common.collect.Maps;

import net.sf.cglib.beans.BeanGenerator;

import net.sf.cglib.beans.BeanMap;

import org.apache.commons.beanutils.PropertyUtilsBean;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.beans.PropertyDescriptor;

import java.util.Map;

/**

 * 动态为bean添加字段

 * @Author gongl

 * @Create 2022-01-11

 */

public class DynamicBeanUtils {

    private static final Logger logger = LoggerFactory.getLogger(DynamicBeanUtils.class);

    public static Object getTarget(Object dest, Map<String, Object> addProperties) {

        PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();

        //得到原对象的属性

        PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);

        Map<String, Class<?>> propertyMap = Maps.newHashMap();

        for (PropertyDescriptor d : descriptors) {

            if (!"class".equalsIgnoreCase(d.getName())) {

                propertyMap.put(d.getName(), d.getPropertyType());

            }

        }

        addProperties.forEach((k, v) -> propertyMap.put(k, v.getClass()));

        //构建新的对象

        DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);

        for (Map.Entry<String, Class<?>> entry : propertyMap.entrySet()) {

            try {

                if (!addProperties.containsKey(entry.getKey())) {//原来的值

                    dynamicBean.setValue(entry.getKey(), propertyUtilsBean.getNestedProperty(dest, entry.getKey()));

                }else {//新增的值

                    dynamicBean.setValue(entry.getKey(), addProperties.get(entry.getKey()));

                }

            } catch (Exception e) {

                logger.error(e.getMessage(), e);

            }

        }

        return dynamicBean.getTarget();

    }

    private static class DynamicBean {

        /**

         * 目标对象

         */

        private Object target;

        /**

         * 属性集合

         */

        private BeanMap beanMap;

        public DynamicBean(Class<?> superclass, Map<String, Class<?>> propertyMap) {

            this.target = generateBean(superclass, propertyMap);

            this.beanMap = BeanMap.create(this.target);

        }

        /**

         * bean 添加属性和值

         *

         * @param property

         * @param value

         */

        public void setValue(String property, Object value) {

            beanMap.put(property, value);

        }

        /**

         * 获取属性值

         *

         * @param property

         * @return

         */

        public Object getValue(String property) {

            return beanMap.get(property);

        }

        /**

         * 获取对象

         *

         * @return

         */

        public Object getTarget() {

            return this.target;

        }

        /**

         * 根据属性生成对象

         *

         * @param superclass

         * @param propertyMap

         * @return

         */

        private Object generateBean(Class<?> superclass, Map<String, Class<?>> propertyMap) {

            BeanGenerator generator = new BeanGenerator();

            if (null != superclass) {

                generator.setSuperclass(superclass);

            }

            BeanGenerator.addProperties(generator, propertyMap);

            return generator.create();

        }

    }

}

测试

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

public static class TestBean{

        private String name;

        public String getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

        TestBean bean = new TestBean();

        bean.setName("张三");

        Map<String, Object> map = new HashMap<>();

        map.put("age", 29);

        //添加参数age--->29

        Object obj = DynamicBeanUtils.getTarget(bean, map);

        //打印结果

        Method[] declaredMethods = obj.getClass().getDeclaredMethods();

        for(Method method:declaredMethods){

            if(method.getName().startsWith("get")){

                Object o=method.invoke(obj);

                System.out.println("属性值get方法->"+o);

            }

        }

    }

结果打印出name和age的值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值