当知道某个类,想获取类上的某个属性的值时,有时会用到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;}
如果觉得《Java反射获取对象的属性值》对你有帮助,请点赞、收藏,并留下你的观点哦!