标签:name exception reac 根据 tcl target imp shm ISE
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对象的再次动态新增属性和属性值。
标签:name exception reac 根据 tcl target imp shm ISE
原文地址:https://www.cnblogs.com/zhuiyishanran/p/12937897.html