package org.pulloid;
import java.util.HashMap;
/**
* Is responsible for instantiating objects in a {@link Cursor}.
* This is done 3 different ways:
* - By instantiating a class (use {@link #Reflector(Class)})
* - By using a {@link ObjectFactory} (use {@link #Reflector(ObjectFactory)})
* - By creating a Map (use {@link #Reflector()})
*
*
* @author Romain Laboisse labrom@gmail.com
*
* @param The type of objects to create. If this Reflector is intended to work with a Map, T MUST be Map for things to work as expected.
*/
class Reflector {
T object;
private Class clazz;
private ObjectFactory factory;
/**
* This reflector will use a Map. This is the same as calling any of the
* other constructors will a null argument.
*/
Reflector() {
// In this case we'll use a map
}
/**
*
* @param clazz The class to instantiate. If null, will use a Map (same a {@link #Reflector()}).
*/
Reflector(Class clazz) {
this.clazz = clazz;
}
/**
*
* @param f The object factory. If null, will use a Map (same a {@link #Reflector()}).
*/
Reflector(ObjectFactory f) {
this.factory = f;
}
@SuppressWarnings("unchecked")
T createObject() {
// If there's a factory, use it
if(factory != null) {
object = factory.createObject();
return object;
}
// If there's no class, use a Map
if(clazz == null) {
// T must be Map for things to work as expected.
object = (T)new HashMap();
return object;
}
// There's a class, try to instantiate from it
try {
object = clazz.newInstance();
} catch (IllegalAccessException e) {
throw new CursorException(e);
} catch (InstantiationException e) {
throw new CursorException(e);
}
return object;
}
public void set(FieldSetter setter, Object value) {
set(setter, value, null);
}
public void set(FieldSetter setter, Object value, StringTransformer> transformer) {
Object valueToSet = value;
if(transformer != null && value instanceof String) {
valueToSet = transformer.transform((String)value);
}
setter.set(object, valueToSet);
}
}