@Test public void testGetObjectFieldValue() { Person person = new Person(); person.setId(1L); person.setName("storezhang"); Assert.assertEquals(person.getId(), ObjectUtils.fieldValue(person, "id")); Assert.assertEquals(person.getName(), ObjectUtils.fieldValue(person, "name")); }
public static <T> T fieldValue(Object obj, String fieldName) { T t = null; if (null == obj || StringUtils.isBlank(fieldName)) { return t; } Class<?> clazz = obj.getClass(); Field field = null; for(; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName) ; } catch (Exception e) { continue; } } if (null != field) { field.setAccessible(true); try { t = (T) field.get(obj); } catch (Exception e) { t = null; } } return t; }
ObjectUtils { public static <T> T fieldValue(Object obj, String fieldName) { T t = null; if (null == obj || StringUtils.isBlank(fieldName)) { return t; } Class<?> clazz = obj.getClass(); Field field = null; for(; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName) ; } catch (Exception e) { continue; } } if (null != field) { field.setAccessible(true); try { t = (T) field.get(obj); } catch (Exception e) { t = null; } } return t; } }
ObjectUtils { public static <T> T fieldValue(Object obj, String fieldName) { T t = null; if (null == obj || StringUtils.isBlank(fieldName)) { return t; } Class<?> clazz = obj.getClass(); Field field = null; for(; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName) ; } catch (Exception e) { continue; } } if (null != field) { field.setAccessible(true); try { t = (T) field.get(obj); } catch (Exception e) { t = null; } } return t; }  }
ObjectUtils { public static <T> T fieldValue(Object obj, String fieldName) { T t = null; if (null == obj || StringUtils.isBlank(fieldName)) { return t; } Class<?> clazz = obj.getClass(); Field field = null; for(; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName) ; } catch (Exception e) { continue; } } if (null != field) { field.setAccessible(true); try { t = (T) field.get(obj); } catch (Exception e) { t = null; } } return t; }  static T fieldValue(Object obj, String fieldName); }
ObjectUtils { public static <T> T fieldValue(Object obj, String fieldName) { T t = null; if (null == obj || StringUtils.isBlank(fieldName)) { return t; } Class<?> clazz = obj.getClass(); Field field = null; for(; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName) ; } catch (Exception e) { continue; } } if (null != field) { field.setAccessible(true); try { t = (T) field.get(obj); } catch (Exception e) { t = null; } } return t; }  static T fieldValue(Object obj, String fieldName);  }