Last active
August 29, 2015 14:18
-
-
Save xcooper/675c012b3b03929583b3 to your computer and use it in GitHub Desktop.
Generate JavaBean instance from Interfaces using CGLIB
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
/** | |
* 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