Java如何通過屬性名獲取Object對象屬性值
更新時間:2024年07月30日 15:43:40 作者:培根芝士
這篇文章主要介紹了Java如何通過屬性名獲取Object對象屬性值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Java通過屬性名獲取Object對象屬性值
通過已知的屬性名稱,從對象里獲取數(shù)據(jù)的方式
通過將Object轉(zhuǎn)為Map
public Object getPropertyValue(Object t,String objProperty) { Map<String, String> objMap = null; try { objMap = BeanUtils.describe(t); return objMap.get(objProperty); } catch (Exception e) { e.printStackTrace(); } return null; }
通過invoke方式
public Object getFieldValueByName(Object o,String fieldName) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = o.getClass().getMethod(getter); return method.invoke(o); } catch (Exception e) { e.printStackTrace(); } return null; }
調(diào)用方式:
//Map方式 Object obj = getPropertyValue(order, "userId"); if (obj != null) { Integer userId = Integer.parseInt((String)obj); } //invoke方式 Object obj = getFieldValueByName(order, "userId"); if (obj != null) { Integer userId = (Integer)obj; }
獲取Object對象中對應(yīng)的屬性的值(使用IEnumerable)
//對象名稱,屬性名 //返回該對象下的數(shù)據(jù)內(nèi)容 public object GetPropertyValue(object info, string field) { if (info == null) return null; Type t = info.GetType(); IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi; return property.First().GetValue(info, null); }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于IDEA創(chuàng)建SpringMVC項目流程圖解
這篇文章主要介紹了基于IDEA創(chuàng)建SpringMVC項目流程圖解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10Java 中Json中既有對象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對象(推薦)
Gson庫是一個功能強大、易于使用的Java序列化/反序列化庫,它提供了豐富的API來支持Java對象和JSON之間的轉(zhuǎn)換,這篇文章主要介紹了Java 中Json中既有對象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對象,需要的朋友可以參考下2024-07-07MyBatis學(xué)習(xí)教程(五)-實現(xiàn)關(guān)聯(lián)表查詢方法詳解
本文給大家介紹mybatis關(guān)聯(lián)查詢,包括一對一關(guān)聯(lián)查詢,一對多關(guān)聯(lián)查詢,代碼簡單易懂,感興趣的朋友一起學(xué)習(xí)吧2016-05-05