說(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開(kāi)始支持)。所以只能返回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ì)象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
public class DynamicBean { private Object object = null ; // 動(dòng)態(tài)生成的類(lèi) private BeanMap beanMap = null ; // 存放屬性名稱(chēng)以及屬性的類(lèi)型 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ì)象中的屬性字段集合處理方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
/** *參數(shù)說(shuō)明: * object : 查詢結(jié)果數(shù)組中對(duì)象。 * moneyMap : 為對(duì)象對(duì)應(yīng)所有月份數(shù)據(jù)集合 * 解釋?zhuān)阂呀?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>(); // 字段 - 字段類(lèi)型 集合 HashMap<String, Object> typeMap = new HashMap<String, Object>(); // 獲取傳入類(lèi) 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)樽侄螌傩?/code> Set<String> monthKeys = moneyMap.keySet(); for (Iterator<String> it = monthKeys.iterator(); it.hasNext();) { String key = (String) it.next(); // 字段類(lèi)型 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)的生成類(lèi)的屬性、并賦值
1、springboot項(xiàng)目中,在build.gradle中,配置jar包
1
2
|
compile( "commons-beanutils:commons-beanutils:1.9.3" ) compile( "cglib:cglib-nodep:3.2.4" ) |
2、創(chuàng)建DynamicBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
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)換的工具類(lèi)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
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)生成類(lè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)生成屬性并且賦值的使用
1
2
3
4
5
6
7
8
9
10
11
|
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è)參考,也希望大家多多支持服務(wù)器之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/WUWENJINWUWENJIN/article/details/83276553