Last active
August 29, 2015 13:56
-
-
Save jnorthrup/8798983 to your computer and use it in GitHub Desktop.
Create a groovy proxy from bean/interface
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 groovy.lang.GroovyClassLoader; | |
import org.apache.commons.beanutils.PropertyUtils; | |
import java.beans.PropertyDescriptor; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
public class GroovyGsonShimFactory { | |
private Map<Class, Method> shimMethods = new LinkedHashMap<>(); | |
private void generateGroovyProxy(Class ifaceClass) { | |
String c1 = ifaceClass.getSimpleName() + "$Proxy"; | |
String s = "public class " + c1 + " implements " + ifaceClass.getCanonicalName() + "\n{"; | |
{ | |
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(ifaceClass); | |
for (PropertyDescriptor p : propertyDescriptors) { | |
String name = p.getName(); | |
String tname = p.getPropertyType().getCanonicalName(); | |
s += "public " + tname + " " + name + ";\n"; | |
s += " " + p.getReadMethod().toGenericString().replace("abstract", "").replace(ifaceClass.getCanonicalName() + ".", "") + "{return " + name + ";};\n"; | |
Method writeMethod = p.getWriteMethod(); | |
if (writeMethod != null) | |
s += " " + writeMethod.toGenericString().replace("abstract", "").replace(ifaceClass.getCanonicalName() + ".", "").replace(")", " v){" + name + "=v;};") + "\n\n"; | |
} | |
} | |
s += "public static " + c1 + | |
" fromJson(String s){return new com.google.gson.Gson().fromJson(s," + c1 + ");};\n"; | |
s += "\n};"; | |
System.err.println("" + s); | |
ClassLoader parent = DefaultDriver.class.getClassLoader(); | |
GroovyClassLoader loader = new GroovyClassLoader(parent); | |
Class gClass = loader.parseClass(s); | |
try { | |
Method shimMethod = gClass.getMethod("fromJson", String.class); | |
shimMethods.put(ifaceClass, shimMethod); | |
} catch (NoSuchMethodException e) { | |
e.printStackTrace(); //todo: review for a purpose | |
} | |
} | |
public <T> T getShim(String json, Class<T> ifaceClass) { | |
if (!shimMethods.containsKey(ifaceClass)) generateGroovyProxy(ifaceClass); | |
T shim = null;//= gson().shimMethods(json, CowSchema.class); | |
try { | |
shim = (T) shimMethods.get(ifaceClass).invoke(null, json); | |
} catch (IllegalAccessException | InvocationTargetException e) { | |
e.printStackTrace(); //todo: review for a purpose | |
} | |
return shim; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment