Java如何通过属性名获取Object对象属性值
作者:培根芝士
这篇文章主要介绍了Java如何通过属性名获取Object对象属性值问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Java通过属性名获取Object对象属性值
通过已知的属性名称,从对象里获取数据的方式
通过将Object转为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;
}调用方式:
//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对象中对应的属性的值(使用IEnumerable)
//对象名称,属性名
//返回该对象下的数据内容
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);
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
