Last active
March 18, 2019 02:37
-
-
Save guozi/0e3e5c041ccfc5c064689cef6279ae62 to your computer and use it in GitHub Desktop.
java 反射获得类的属性和父类的属性,属性值
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
Class<?> clazz = param.getClass(); | |
for (; clazz != Object.class; clazz = clazz.getSuperclass()) { | |
Field[] fields = clazz.getDeclaredFields(); | |
for (Field field : fields) { | |
int mod = field.getModifiers(); | |
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { | |
continue; | |
} | |
field.setAccessible(true); | |
Object val = field.get(param); | |
if (val instanceof String) { | |
String value = (String) val; | |
if (StringUtils.isNotEmpty(value)) { | |
value = new String(value.getBytes("ISO8859-1"), "utf-8"); | |
} | |
field.set(param, value); | |
} | |
} | |
} | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Object getFieldVal(final Object obj, final String fieldName, final boolean throwException) { | |
if (obj != null) { | |
for (Class<?> classOrSuperclass = obj.getClass(); classOrSuperclass != null; // | |
classOrSuperclass = classOrSuperclass.getSuperclass()) { | |
try { | |
final Field field = classOrSuperclass.getDeclaredField(fieldName); | |
if (!field.isAccessible()) { | |
field.setAccessible(true); | |
} | |
return field.get(obj); | |
} catch (final NoSuchFieldException e) { | |
// Try parent | |
} catch (final Throwable e) { | |
if (throwException) { | |
throw new IllegalArgumentException("Could not get value of field \"" + fieldName + "\"", e); | |
} | |
} | |
} | |
if (throwException) { | |
throw new IllegalArgumentException("Field \"" + fieldName + "\" doesn't exist"); | |
} | |
} else if (throwException) { | |
throw new NullPointerException("Can't get field value for null object"); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment