Java 類動(dòng)態(tài)添加屬性字段的操作
說明:
做項(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 。主要用來處理對(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. 原來對(duì)象, 及需要拼接到對(duì)象中的屬性字段集合處理方法。
/**
*參數(shù)說明:
* 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;
}
做筆記使用, 說不定以后還會(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)文章
關(guān)于集合和字符串的互轉(zhuǎn)實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄P(guān)于集合和字符串的互轉(zhuǎn)實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-08-08
Java匿名內(nèi)部類導(dǎo)致內(nèi)存泄露的原因與解決方案詳解
這篇文章主要為大家詳細(xì)介紹了Java因?yàn)槟涿麅?nèi)部類導(dǎo)致內(nèi)存泄露的原因以及其解決方案,文中的示例代碼講解詳細(xì),希望對(duì)大家有所幫助2022-11-11
快速上手Mybatis-plus結(jié)構(gòu)構(gòu)建過程
這篇文章主要介紹了快速上手Mybatis-plus結(jié)構(gòu)構(gòu)建過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Java8 Optional優(yōu)雅空值判斷的示例代碼
這篇文章主要介紹了Java8 Optional優(yōu)雅空值判斷的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05
java堆棧類使用實(shí)例(java中stack的使用方法)
java中stack的使用方法,堆棧是一種"后進(jìn)先出"(LIFO) 的數(shù)據(jù)結(jié)構(gòu), 只能在一端進(jìn)行插入(稱為"壓棧") 或刪除 (稱為"出棧")數(shù)據(jù)的操作,下面看示例吧2013-12-12
使用maven創(chuàng)建普通項(xiàng)目命令行程序詳解
大部分使用maven創(chuàng)建的是web項(xiàng)目,這里使用maven創(chuàng)建一個(gè)命令行程序,目的是讓大家了解maven特點(diǎn)和使用方式,有需要的朋友可以借鑒參考下2021-10-10
使用Swagger時(shí)Controller中api接口顯示不全的問題分析及解決
swagger是一個(gè)十分好用的api接口管理、測(cè)試框架,現(xiàn)在越來越多的人使用這個(gè)做接口的測(cè)試和管理,但經(jīng)常遇到Controller中的api接口顯示不全的問題,所以本文給大家詳細(xì)分析了問題以及解決方法,需要的朋友可以參考下2024-02-02
SpringMVC如何域?qū)ο蠊蚕頂?shù)據(jù)
在Spring MVC中,可以使用域?qū)ο髞砉蚕頂?shù)據(jù),域?qū)ο笫且粋€(gè)Map類型的對(duì)象,可以在請(qǐng)求處理方法之間共享數(shù)據(jù),本文給大家介紹SpringMVC 域?qū)ο蠊蚕頂?shù)據(jù)的示例代碼,一起看看吧2023-09-09
SpringBoot整合EasyExcel實(shí)現(xiàn)Excel表格導(dǎo)出功能
這篇文章主要介紹了SpringBoot整合EasyExcel實(shí)現(xiàn)Excel表格導(dǎo)出功能,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07

