动态给类添加属性

pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ymqx</groupId>
  <artifactId>MyTest</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>MyTest</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <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>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>2.0.0</version>
    </dependency>
  </dependencies>

</project>

DynamicBeanUtils

package com.ymqx.动态给类添加属性;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;
import org.apache.commons.beanutils.PropertyUtilsBean;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;


/*
 * 思路:
 * 1、通过commons-beanutils包下的类 PropertyUtilsBean 获取目标对象的属性
 * 2、将需要新增的属性加入原对象的属性集合
 * 3、通过cglib包下的类 BeanGenerator 创建新的Bean
 * 4、遍历新创建的bean属性,为新增的属性赋值
 *
 */
public class DynamicBeanUtils {
    public static Object getTarget(Object dest, Map<String, Object> addProperties) {
        PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
        //得到原对象的属性
        PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);
        Map<String, Class<?>> propertyMap = new HashMap<>();
        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);
        propertyMap.forEach((k, v) -> {
            try {
                if (!addProperties.containsKey(k)) {
                    //原来的值
                    dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k));
                }else {
                    //新增的值
                    dynamicBean.setValue(k, addProperties.get(k));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        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();
        }
    }
}

DynamicBeanUtils2

package com.ymqx.动态给类添加属性;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

/*
 * 思路:
 * 1、通过cglib包下的类 beanMap 获取目标对象的属性
 * 2、将需要新增的属性加入原对象的属性集合
 * 3、通过cglib包下的类 BeanGenerator 创建新的Bean
 * 4、遍历新创建的bean属性,为新增的属性赋值
 *
 */

public class DynamicBeanUtils2 {
    public static Object getTarget(Object dest, Map<String, Object> addProperties) {
        // 获取原对象属性集合
        BeanMap beanMap = BeanMap.create(dest);
        Map<String, Class<?>> propertyMap = new HashMap<>();

        beanMap.forEach((k, v) -> {
            propertyMap.put(k.toString(), v.getClass());
        });
        addProperties.forEach((k, v) -> propertyMap.put(k, v.getClass()));

        //构建新的对象
        DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);
        propertyMap.forEach((k, v) -> {
            try {
                if (!addProperties.containsKey(k)) {
                    //原来的值
                    dynamicBean.setValue(k, beanMap.get(k));
                }else {
                    //新增的值
                    dynamicBean.setValue(k, addProperties.get(k));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        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();
        }
    }
}

TestBean

package com.ymqx.动态给类添加属性;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class TestBean {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void printFields(Object obj) throws IllegalAccessException {
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field f : declaredFields) {
            f.setAccessible(true);
            System.out.println(f.getName() + "=" + f.get(obj));
        }
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        TestBean bean = new TestBean();
        bean.setName("张三");
        printFields(bean);
        System.out.println("User:"+ JSON.toJSONString(bean));

        Map<String, Object> map = new HashMap<>();
        map.put("age", 29);
        //添加参数age--->29
        Object obj = DynamicBeanUtils.getTarget(bean, map);

        //打印结果
        printFields(obj);
        System.out.println("User:"+JSON.toJSONString(obj));


        System.out.println("-----------------");


        TestBean bean2 = new TestBean();
        bean2.setName("张三");
        printFields(bean2);
        System.out.println("User:"+ JSON.toJSONString(bean2));

        Map<String, Object> map2 = new HashMap<>();
        map2.put("age", 29);
        //添加参数age--->29
        Object obj2 = DynamicBeanUtils2.getTarget(bean2, map2);

        //打印结果
        printFields(obj2);
        System.out.println("User:"+JSON.toJSONString(obj2));
    }
}

运行结果:

name=张三
User{"name":"张三"}
$cglib_prop_name=张三
$cglib_prop_age=29
User{"age":29,"name":"张三"}
-----------------
name=张三
User{"name":"张三"}
$cglib_prop_name=张三
$cglib_prop_age=29
User{"age":29,"name":"张三"}

动态的为实体字段添加注解/注解属性
https://blog.csdn.net/Adda_Chen/article/details/120869545

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,属性通常是在定义时声明的,但是如果需要动态添加属性,可以使用Java反射机制来实现。具体步骤如下: 1. 获取该的Class对象,可以使用Class.forName("的全限定名")方法或者的.class属性获取。 2. 使用Class的getDeclaredFields()方法获取该的所有属性。 3. 使用Class的getDeclaredMethod()方法获取该的set和get方法。 4. 使用Field的setAccessible(true)方法设置为可访问(因为有些属性可能是私有的)。 5. 使用Field的set()方法给该的实例对象设置属性值。 示例代码如下: ``` public class Test { public static void main(String[] args) throws Exception { // 获取的Class对象 Class<?> clazz = Class.forName("com.example.Person"); // 获取该的所有属性 Field[] fields = clazz.getDeclaredFields(); // 遍历属性添加属性 Field newField = new Field("newField", String.class); Field[] newFields = new Field[fields.length + 1]; System.arraycopy(fields, 0, newFields, 0, fields.length); newFields[fields.length] = newField; // 定义set和get方法 Method setNewField = clazz.getDeclaredMethod("setNewField", String.class); Method getNewField = clazz.getDeclaredMethod("getNewField"); // 创建对象并设置新属性值 Object obj = clazz.newInstance(); newField.setAccessible(true); newField.set(obj, "newFieldValue"); // 调用set方法设置新属性值 setNewField.invoke(obj, "newFieldValue"); // 调用get方法获取新属性值 System.out.println(getNewField.invoke(obj)); } } class Person { private String name; private int age; public void setNewField(String value) { this.newField = value; } public String getNewField() { return this.newField; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会叫的狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值