Created
August 26, 2013 09:15
-
-
Save sachin-handiekar/6339523 to your computer and use it in GitHub Desktop.
Injecting mock objects on an annotation. e.g. You can inject a mock object on a @PersistenceContext annotated field
This file contains hidden or 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.annotation.Annotation; | |
import java.lang.reflect.Field; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import javax.persistence.PersistenceContext; | |
public class ClassInjector { | |
private static final List<Class<? extends Annotation>> ANNOTATIONS; | |
static { | |
ANNOTATIONS = new ArrayList<Class<? extends Annotation>>(); | |
ANNOTATIONS.add(PersistenceContext.class); | |
} | |
final Map<Class<?>, Object> mappings = new HashMap<Class<?>, Object>(); | |
public void inject(final Object bean) throws Exception { | |
for (final Field field : getClassAnnotatedFields(bean)) { | |
injectField(field, bean); | |
} | |
} | |
public void assign(final Class<?> type, final Object instance) { | |
mappings.put(type, instance); | |
} | |
private void injectField(final Field field, final Object bean) throws Exception { | |
final Object instanceToInject = mappings.get(field.getType()); | |
if (!field.isAccessible()) { | |
field.setAccessible(true); | |
} | |
field.set(bean, instanceToInject); | |
} | |
private List<Field> getClassAnnotatedFields(final Object bean) { | |
final Class<? extends Object> beanClass = bean.getClass(); | |
final List<Field> annotatedFields = new ArrayList<Field>(); | |
for (final Field field : beanClass.getDeclaredFields()) { | |
if (hasAnnotation(field)) { | |
annotatedFields.add(field); | |
} | |
} | |
return annotatedFields; | |
} | |
private static boolean hasAnnotation(final Field field) { | |
for (final Class<? extends Annotation> annotation : ANNOTATIONS) { | |
if (field.isAnnotationPresent(annotation)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment