当知道某个类,想获取类上的某个属性的值时,有时会用到Java的反射机制,如下参考:
/**
* 反射获取对象的属性值
* @param object 对象(要遍历的对象)
* @param targetFieldName 属性名
* @return 属性值
*/
private static Object getFieldValueByObject(Object object, String targetFieldName) {
Object result = null;
Class objClass = object.getClass();
Field[] fields = objClass.getDeclaredFields();
for (Field field : fields) {
String currentFieldName = "";
try {
boolean hasJsonProperty = field.isAnnotationPresent(JsonProperty.class);
if (hasJsonProperty) {
currentFieldName = field.getAnnotation(JsonProperty.class).value();
} else {
currentFieldName = field.getName();
}
if (currentFieldName.toUpperCase().equals(targetFieldName.toUpperCase())) {
//设置属性的可访问性
field.setAccessible(true);
result = field.get(object);
return result;
}
} catch (SecurityException e) {
// 安全性异常
throw new RuntimeException("获取对象的属性值安全性异常:" + e.getMessage());
} catch (IllegalArgumentException e) {
// 非法参数
throw new RuntimeException("获取对象的属性值非法参数异常:" + e.getMessage());
} catch (IllegalAccessException e) {
// 无访问权限
throw new RuntimeException("获取对象的属性值无访问权限异常:" + e.getMessage());
}
}
return result;
}
版权声明:本文为yiyelanxin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。