Skip to content

Instantly share code, notes, and snippets.

@groupsky
Created June 25, 2011 14:15
Show Gist options
  • Save groupsky/1046530 to your computer and use it in GitHub Desktop.
Save groupsky/1046530 to your computer and use it in GitHub Desktop.
Reflections based ParameterizedFactory
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
// from http://code.google.com/p/reflections/
import org.reflections.Reflections;
/**
* @author Geno Roupsky
*
* @param <K>
* The key class, usually an enumeration but could be any comparable
* class
* @param <V>
* The resulting class, usually an interface
* @param <A>
* The annotation that is used to register items. MUST have a single
* value() method of type K
*/
public class ParameterizedFactory<K, V, A extends Annotation> {
private Map<K, Class<? extends V>> items = new HashMap<K, Class<? extends V>>();
public ParameterizedFactory(Class<V> result, Class<A> annotation) throws SecurityException, NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Reflections reflections = new Reflections("");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation);
for (Class<?> clz : annotated) {
if (result.isAssignableFrom(clz)) {
@SuppressWarnings("unchecked")
Class<? extends V> clr = (Class<? extends V>) clz;
A annot = clz.getAnnotation(annotation);
Method method = annot.getClass().getDeclaredMethod("value", new Class<?>[] {});
@SuppressWarnings("unchecked")
K key = (K) method.invoke(annot, new Object[] {});
items.put(key, clr);
}
}
}
public V getItem(K key) throws InstantiationException, IllegalAccessException {
if ((key == null) || "".equals(key)) {
throw new IllegalArgumentException("No key supplied!");
}
if (items.containsKey(key)) {
return items.get(key).newInstance();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment