Skip to content

Instantly share code, notes, and snippets.

@smat
Created December 7, 2011 14:57
Show Gist options
  • Save smat/1443110 to your computer and use it in GitHub Desktop.
Save smat/1443110 to your computer and use it in GitHub Desktop.
Generate Mock-objects from a hashmap
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
public class ProxyGenerator {
private HashMap<String, Object> properties;
private ProxyGenerator(HashMap<String, Object> properties) {
this.properties = new HashMap<String, Object>(properties);
}
public static <T> T createProxyObject(HashMap<String, Object> properties, Class<T> clazz) {
ProxyGenerator proxyGenerator = new ProxyGenerator(properties);
ResultSetInvocationHandler handler = proxyGenerator.new ResultSetInvocationHandler();
Class<?>[] classes = {clazz};
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), classes, handler);
}
private class ResultSetInvocationHandler implements InvocationHandler {
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
if (StringUtils.startsWith(method.getName(), "get")) {
return properties.get(WordUtils.uncapitalize(method.getName().substring(3)));
}
throw new NotImplementedException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment