Skip to content

Instantly share code, notes, and snippets.

@xcooper
Last active August 29, 2015 14:18
Show Gist options
  • Save xcooper/675c012b3b03929583b3 to your computer and use it in GitHub Desktop.
Save xcooper/675c012b3b03929583b3 to your computer and use it in GitHub Desktop.
Generate JavaBean instance from Interfaces using CGLIB
/**
* Dynamically create a Javabean from Interfaces.
* It's ugly, but works ;)
*
*/
@Grapes(@Grab(group='cglib', module='cglib', version='3.1'))
import net.sf.cglib.beans.*
import net.sf.cglib.proxy.*
interface Test {
String getStr()
void setStr(String str)
}
// create a class implement the interfaces
ClassLoader cl = this.getClass().getClassLoader()
Class concreteClass = Proxy.getProxyClass(cl, [Test.class] as Class[])
// create a super class implement the interfaces
Enhancer eh = new Enhancer()
eh.setInterfaces([Test.class] as Class[])
eh.setCallbackType(NoOp.class)
Class t1 = eh.createClass()
// put all together
BeanGenerator bg = new BeanGenerator()
BeanGenerator.addProperties(bg, concreteClass)
bg.setSuperclass(t1)
Test t = bg.create()
t.setStr("Hello")
println t.getStr()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment