当知道某个类,想获取类上的某个属性的值时,有时会用到Java的反射机制,如下参考:
private static Object getFieldValueByObject(Object object, String targetFieldName) {
Class objClass = object.getClass();
Field[] fields = objClass.getDeclaredFields();
for (Field field : fields) {
String currentFieldName = "";
boolean hasJsonProperty = field.isAnnotationPresent(JsonProperty.class);
currentFieldName = field.getAnnotation(JsonProperty.class).value();
currentFieldName = field.getName();
if (currentFieldName.toUpperCase().equals(targetFieldName.toUpperCase())) {
field.setAccessible(true);
result = field.get(object);
} catch (SecurityException e) {
throw new RuntimeException("获取对象的属性值安全性异常:" + e.getMessage());
} catch (IllegalArgumentException e) {
throw new RuntimeException("获取对象的属性值非法参数异常:" + e.getMessage());
} catch (IllegalAccessException e) {
throw new RuntimeException("获取对象的属性值无访问权限异常:" + e.getMessage());