说明:通过已知的属性名称,从对象里获取数据的方式
1 通过将Object转为Map
public static 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;
}
2 通过invoke方式
public static 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, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
测试
public static void main(String[] args) {
Exam exam = new Exam();
exam.setTag("AAAAAA");
System.out.println(getFieldValueByName(exam,"tag"));
System.out.println(getPropertyValue(exam,"tag"));
}
结果
AAAAAA
AAAAAA