Created
April 25, 2014 01:14
-
-
Save nowell-jana/11274902 to your computer and use it in GitHub Desktop.
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
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