Skip to content

Instantly share code, notes, and snippets.

@Pooh3Mobi
Created February 4, 2016 06:17
Show Gist options
  • Save Pooh3Mobi/8dda3eb3efbb93c08809 to your computer and use it in GitHub Desktop.
Save Pooh3Mobi/8dda3eb3efbb93c08809 to your computer and use it in GitHub Desktop.
public class ReflectionUtil {
public static Object getField(Object object, String strName) throws NoSuchFieldException, IllegalAccessException {
if(object == null || object.getClass() == null) return null;
Field field = object.getClass().getField(strName);
return field.get(object);
}
public static Object getDeclaredField(Object obj, String name)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
return f.get(obj);
}
public static void setValueToDeclaredField(Object obj, String name, Object value)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
f.set(obj, value);
}
public static void setValueToDeclaredFieldFromSuperClass(Object obj, String name, Object value)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = getFieldFromSuperClass(obj.getClass(), name);
f.setAccessible(true);
f.set(obj, value);
}
public static Field getFieldFromSuperClass(Class clazz, String fieldName)
throws NoSuchFieldException {
Field field = null;
while (clazz != null) {
try {
field = clazz.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
}
if (field == null) {
throw new NoSuchFieldException();
}
return field;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment