Java動態Bean


package com.xxx.bean.entity;

import com.xxx.base.common.exception.BaseException;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

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

/**
 * Created by xxxtech on 2020/4/23.
 */
public class DynamicBean {
    /**
     * 目標對象
     */
    private Object target;

    /**
     * 屬性集合
     */
    private BeanMap beanMap;

    /**
     * propertyMap: 屬性名稱和所屬類型map
     */
    private Map<String, Class> propertyMap;


    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 (superclass != null) {
            generator.setSuperclass(superclass);
        }
        this.propertyMap = propertyMap;
        BeanGenerator.addProperties(generator, propertyMap);
        return generator.create();
    }

    /**
     * */
    public <T> DynamicBean addPropertyToDyBean(T vo) throws BaseException {
        try {
            Field[] arr = vo.getClass().getDeclaredFields();
            Map<String, Class> propertyMap = new HashMap<>();
            if (this.propertyMap != null && !this.propertyMap.isEmpty())
                propertyMap.putAll(this.propertyMap);
            for (Field field : arr)
                propertyMap.put(field.getName(), field.getType());
            DynamicBean dyBean = new DynamicBean(vo.getClass(), propertyMap);
            beanMap.forEach((k, v) -> {
                dyBean.setValue(k.toString(), v);
            });
            for (Field field : arr)
                dyBean.setValue(field.getName(), com.xxx.bean.util.ReflectionUtils.invokeGetter(vo, field.getName()));
            return dyBean;
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage(), ex);
        }
    }
}

參考文章:原作者找不到了...

在原來的基礎上加了addPropertyToDyBean方法,用來實現對DynamicBean對象的再次動態新增屬性和屬性值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM