Java為實體類動態添加屬性的方法詳解

可以給已有實體類動態的添加字段並返回新的實體對象,不影響原來的實體對象結構。

添加依賴

        <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>

代碼

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();
        }
    }
}

測試

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的值

到此這篇關於Java為實體類動態添加屬性的方法詳解的文章就介紹到這瞭,更多相關Java實體類添加屬性內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: