Skip to content

Instantly share code, notes, and snippets.

@Bastian
Created July 20, 2014 10:51
Show Gist options
  • Save Bastian/663f3cd033c0519e6f86 to your computer and use it in GitHub Desktop.
Save Bastian/663f3cd033c0519e6f86 to your computer and use it in GitHub Desktop.
package de.oppermann.bastian.lib.miscellaneous;
import java.lang.reflect.Field;
/**
* Class that helps with reflection.
*/
public class ReflectionUtil {
// no instance
private ReflectionUtil() { }
/**
* Gets a {@link Field} from a Object with a given name.
*
* @param from The object that contains the field.
* @param name The name of the field.
* @return The field with the given name. <code>null</code> if there is no field with this name.
*/
@SuppressWarnings("unchecked")
public static <T> T getField(Object from, String name) {
if (from == null)
throw new IllegalArgumentException("from cannot be null");
if (name == null)
throw new IllegalArgumentException("name cannot be null");
Class<?> checkClass = from.getClass();
do {
try {
Field field = checkClass.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(from);
} catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { }
} while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));
return null;
}
/**
* Sets the value of a private field.
*
* @param object The object.
* @param name The name of the field.
* @param value The value to set.
*/
public static void setPrivateField(Object object, String name, Object value) {
if (object == null)
throw new IllegalArgumentException("from cannot be null");
if (name == null)
throw new IllegalArgumentException("name cannot be null");
Class<?> checkClass = object.getClass();
do {
try {
Field field = checkClass.getDeclaredField(name);
field.setAccessible(true);
field.set(object, value);
} catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { }
} while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment