Last active
August 29, 2015 14:26
-
-
Save petitviolet/2ad7ee9e325b2eeb3b3d to your computer and use it in GitHub Desktop.
Java reflection utility
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 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