Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petitviolet/2ad7ee9e325b2eeb3b3d to your computer and use it in GitHub Desktop.
Save petitviolet/2ad7ee9e325b2eeb3b3d to your computer and use it in GitHub Desktop.
Java reflection utility
public class ReflectionUtil {
private Field extractField(Object target, String name) {
for (Field field : target.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (name.equals(field.getName())) {
return field;
}
}
return null;
}
public static Object extractMember(Object target, String name) throws IllegalAccessException {
Field field = extractField(target, name);
return field == null ? null : field.get(target);
}
public static void setPrivateMember(Object target, String name, Object newValue) throws IllegalAccessException {
Field field = extractField(target, name);
if (field == null) {
return;
}
Object targetField = field.get(target);
field.set(targetField, newValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment