Skip to content

Instantly share code, notes, and snippets.

@nowell-jana
Created April 25, 2014 01:14
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 nowell-jana/11274902 to your computer and use it in GitHub Desktop.
Save nowell-jana/11274902 to your computer and use it in GitHub Desktop.
import java.lang.reflect.Field;
public class ReflectUtils {
/* Reflectively replaces instances of clazz on supplied instance with supplied mock object */
public static String injectMockByClass(Class<?> clazz, Object instance, Object mock) {
Field[] fields = instance.getClass().getDeclaredFields();
String msg = "No instances of " + clazz.getCanonicalName() + " found";
for (Field field : fields) {
if (clazz.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true);
field.set(instance, mock);
msg = "Injected " + mock.getClass().getCanonicalName()
+ " instance into field " + field.getName()
+ " of " + instance.getClass().getName();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return msg;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment