io.ebean.WithStaticFinder Maven / Gradle / Ivy
package io.ebean;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Used to replace a "Finder" that is located as a static field (typically on an Model entity bean).
*
* This uses reflection to get/set the finder implementation with the ability to replace the original implementation
* with the test double and restoring the original.
*/
public class WithStaticFinder {
final Class beanType;
String fieldName;
Field field;
Object original;
Object testDouble;
/**
* Construct with a given bean type.
*/
public WithStaticFinder(Class beanType) {
this.beanType = beanType;
}
/**
* Construct with a given bean type.
*/
public WithStaticFinder(Class beanType, String fieldName) {
this.beanType = beanType;
this.fieldName = fieldName;
}
/**
* Set the test double instance to use after useTestDouble() has been called.
*
* Note that the test double instance is not set until useTestDouble()
is called.
*/
public WithStaticFinder as(Object testDouble) throws FinderFieldNotFoundException {
try {
this.testDouble = testDouble;
this.field = findField();
this.field.setAccessible(true);
try {
Field modifiersField = Field.class.getDeclaredField("modifiers");
/**
* If the project using this library has a SecurityManager set up, permission may be denied.
* Therefor, running this as a privileged action.
*/
AccessController.doPrivileged((PrivilegedAction