Created
December 7, 2011 14:57
-
-
Save smat/1443110 to your computer and use it in GitHub Desktop.
Generate Mock-objects from a hashmap
This file contains 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 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