Java 類動(dòng)態(tài)添加屬性字段的操作
說(shuō)明:
做項(xiàng)目中遇到一種場(chǎng)景,需要根據(jù)查詢時(shí)間段, 獲取時(shí)間段中中每個(gè)月份對(duì)應(yīng)的金額(費(fèi)用統(tǒng)計(jì))。
如截圖中的兩列
因?yàn)榱惺莿?dòng)態(tài)的, 首先想到的就是后天拼接JSON格式字符串, 然后返回到前臺(tái), 組裝表頭及內(nèi)容。
但是當(dāng)前系統(tǒng)中easyUI版本為1.2,并不支持 data屬性(官方從1.3.2開始支持)。所以只能返回list<T> 格式。
網(wǎng)上一搜相關(guān)代碼很多, 看客可以自己搜索一下。 我這里記錄一下我當(dāng)時(shí)使用場(chǎng)景及用法,已備以后使用。
1.需要引用cglib jar包, 我用的版本是2.2
2.建一個(gè)實(shí)體對(duì)象 DynamicBean.java 。主要用來(lái)處理對(duì)象。
public class DynamicBean { private Object object = null; // 動(dòng)態(tài)生成的類 private BeanMap beanMap = null; // 存放屬性名稱以及屬性的類型 public DynamicBean() { super(); } public DynamicBean(Map propertyMap) { this.object = generateBean(propertyMap); this.beanMap = BeanMap.create(this.object); } /** * @param propertyMap * @return */ private Object generateBean(Map propertyMap) { BeanGenerator generator = new BeanGenerator(); Set keySet = propertyMap.keySet(); for (Iterator<String> i = keySet.iterator(); i.hasNext();) { String key = (String) i.next(); generator.addProperty(key, (Class) propertyMap.get(key)); } return generator.create(); } /** * ��bean���Ը�ֵ * @param property ������ * @param value ֵ */ public void setValue(Object property, Object value) { beanMap.put(property, value); } /** * ͨ���������õ�����ֵ * @param property ������ * @return ֵ */ public Object getValue(String property) { return beanMap.get(property); } /** * 返回新生成的對(duì)象 * @return */ public Object getObject() { return this.object; } }
3. 原來(lái)對(duì)象, 及需要拼接到對(duì)象中的屬性字段集合處理方法。
/** *參數(shù)說(shuō)明: * object : 查詢結(jié)果數(shù)組中對(duì)象。 * moneyMap : 為對(duì)象對(duì)應(yīng)所有月份數(shù)據(jù)集合 * 解釋:已經(jīng)查詢出一組賬單對(duì)象集合List<Bill> , 而moneyMap為對(duì)象中的一個(gè)屬性 * Map<String,Bigdecimal>, 存放了月份及金額 */ private Object dynamicClass(Object object, Map<String, BigDecimal> moneyMap) throws Exception { // 字段 - 值 集合 HashMap<String, Object> returnMap = new HashMap<String, Object>(); // 字段 - 字段類型 集合 HashMap<String, Object> typeMap = new HashMap<String, Object>(); // 獲取傳入類 Class<? extends Object> type = object.getClass(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); // 獲取對(duì)象中已存在的數(shù)據(jù) for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class") && !propertyName.equals("monthMap")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(object, new Object[0]); if (result != null) { returnMap.put(propertyName, result); } else { String propertyType = descriptor.getPropertyType().toString(); if (propertyType.contains("java.math.BigDecimal")) { returnMap.put(propertyName, new BigDecimal(0)); } else { returnMap.put(propertyName, ""); } } typeMap.put(propertyName, descriptor.getPropertyType()); } } // 獲取月份數(shù)據(jù), 變?yōu)樽侄螌傩? Set<String> monthKeys = moneyMap.keySet(); for (Iterator<String> it = monthKeys.iterator(); it.hasNext();) { String key = (String) it.next(); // 字段類型 typeMap.put(key, Class.forName("java.math.BigDecimal")); // 字段對(duì)應(yīng)值 returnMap.put(key, moneyMap.get(key)); } // map轉(zhuǎn)換成實(shí)體對(duì)象 DynamicBean bean = new DynamicBean(typeMap); // 賦值 Set<String> keys = typeMap.keySet(); for (Iterator<String> it = keys.iterator(); it.hasNext();) { String key = (String) it.next(); bean.setValue(key, returnMap.get(key)); } Object obj = bean.getObject(); return obj; }
做筆記使用, 說(shuō)不定以后還會(huì)用到。
補(bǔ)充:java動(dòng)態(tài)的生成類的屬性、并賦值
1、springboot項(xiàng)目中,在build.gradle中,配置jar包
compile("commons-beanutils:commons-beanutils:1.9.3") compile("cglib:cglib-nodep:3.2.4")
2、創(chuàng)建DynamicBean
import java.util.Map; import net.sf.cglib.beans.BeanGenerator; import net.sf.cglib.beans.BeanMap; public class DynamicBean { /** * 目標(biāo)對(duì)象 */ 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); } /** * 獲取對(duì)象 * * @return */ public Object getTarget() { return this.target; } /** * 根據(jù)屬性生成對(duì)象 * * @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(); } }
3、創(chuàng)建ReflecUtil轉(zhuǎn)換的工具類
import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.commons.beanutils.PropertyUtilsBean; import com.sunxung.factoring.entity.DynamicBean; import com.sunxung.factoring.entity.attendanceManagement.AttendanceVo; /** * @className:ReflectUtil * @description:動(dòng)態(tài)生成類的屬性、并且賦值 * @date:2018年4月3日 下午2:33:10 */ public class ReflectUtil { static Logger logger = LogManager.getLogger(ReflectUtil.class); @SuppressWarnings("rawtypes") 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()); } } // add extra properties addProperties.forEach((k, v) -> propertyMap.put(k, v.getClass())); // new dynamic bean DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap); // add old value propertyMap.forEach((k, v) -> { try { // filter extra properties if (!addProperties.containsKey(k)) { dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k)); } } catch (Exception e) { logger.error(e.getMessage(), e); } }); // add extra value addProperties.forEach((k, v) -> { try { dynamicBean.setValue(k, v); } catch (Exception e) { logger.error(e.getMessage(), e); } }); Object target = dynamicBean.getTarget(); return target; } public static void main(String[] args) { AttendanceVo entity = new AttendanceVo(); Map<String, Object> addProperties = new HashMap<>(); addProperties.put("day31", "你好"); AttendanceVo newVo = (AttendanceVo) getTarget(entity, addProperties); System.out.println(newVo.getDay0()); } }
4、在項(xiàng)目中動(dòng)態(tài)生成屬性并且賦值的使用
private AttendanceVo autoDetailNew(SearchAttendanceVo search, AttendanceVo att) { search.setDingdingUserId(att.getDingdingUserId()); List<Attendance> detailList = attendanceMapper.findDetailList(search); Map<String, Object> addProperties = new HashMap<>(); for (Attendance attendance : detailList) { addProperties.put("day" + DateUtil.getDayStringFormatYMD(attendance.getAttendanceDate()), attendance.getRemark()); } AttendanceVo newVo = (AttendanceVo) ReflectUtil.getTarget(att, addProperties); return newVo; }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Druid連接池的自定義過(guò)濾功能實(shí)現(xiàn)方法
在數(shù)據(jù)密集型應(yīng)用中,監(jiān)控和分析數(shù)據(jù)庫(kù)操作對(duì)于確保性能和穩(wěn)定性至關(guān)重要,本文將探討如何實(shí)現(xiàn)一個(gè)自定義的Druid過(guò)濾器來(lái)捕獲數(shù)據(jù)庫(kù)請(qǐng)求并進(jìn)行日志記錄,以輔助開發(fā)和維護(hù)工作,需要的朋友可以參考下2023-11-11mybatis-plus mapper中foreach循環(huán)操作代碼詳解(新增或修改)
這篇文章主要介紹了mybatis-plus mapper中foreach循環(huán)操作代碼詳解(新增或修改),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11Springboot工具類FileCopyUtils使用教程
這篇文章主要介紹了Springboot內(nèi)置的工具類之FileCopyUtils的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-12-12sharding-jdbc實(shí)現(xiàn)分頁(yè)查詢的示例代碼
sharding-jdbc是一個(gè)輕量級(jí)Java框架,它提供了分布式數(shù)據(jù)庫(kù)中間件的功能,支持水平分表和分庫(kù)分表,在分頁(yè)查詢方面,sharding-jdbc支持兩種方式:基于物理分頁(yè)和基于邏輯分頁(yè),本文給大家介紹sharding-jdbc如何實(shí)現(xiàn)分頁(yè)查詢,需要的朋友可以參考下2024-05-05詳解spring security之httpSecurity使用示例
這篇文章主要介紹了詳解spring security之httpSecurity使用示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08Spring框架的環(huán)境搭建和測(cè)試實(shí)現(xiàn)
這篇文章主要介紹了Spring框架的環(huán)境搭建和測(cè)試實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10從內(nèi)存地址解析Java的static關(guān)鍵字的作用
這篇文章主要介紹了從內(nèi)存地址解析Java的static關(guān)鍵字的作用,包括靜態(tài)成員變量和靜態(tài)方法等重要內(nèi)容,需要的朋友可以參考下2015-10-10