静态方法
两种方法都可以获取到,字段对应的是实体类中的成员变量名
/**
* 获取对应字段的值
*
* @param f 字段
* @param t 对象
* @param <T>
* @return
*/
private static <T> String getValue(String f, T t) {
/*Field[] declaredFields = t.getClass().getDeclaredFields();
for (Field field : declaredFields) {
String name = field.getName();
if (name.equals(f)) {
String getField = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
try {
return t.getClass().getMethod(getField).invoke(t).toString();
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
logger.error("根据字段名获取属性值失败" + ExceptionMessage.mess(e));
}
}
}
return null;*/
try {
BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
if (descriptor.getName().equals(f)) {
return descriptor.getReadMethod().invoke(t).toString();
}
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
logger.error("根据字段名获取属性值失败" + ExceptionMessage.mess(e));
}
return null;
}