Given a class name I would like to dynamically create a Groovy class add properties and methods to it. I create the new class using
instance = this.class.cla
a nice variant would be to use the GroovyShell.
def c = """
package de.myCorp.test
class Test {
def a
def b
def c
Test(String c){ this.c = c}
public String greet(){
return "hello "+a
}
public void count(){
(1..4).each{
println it
}
}
}
def class UsingTest {
Test mytest = null
UsingTest (Test test){ this.mytest = test }
def using(){
mytest.greet();
}
}
"""
GroovyShell gs = new GroovyShell()
//I hope this is not a too bad hack ^^
def erg = gs.evaluate(c+";['test':Test, 'using':UsingTest];")
def testclass = erg["test"].newInstance("Charlotte on Ice")
testclass.a = "hugo"
testclass.b = "sepp"
testclass.count()
assert testclass.greet() == "hello hugo"
assert testclass.c == "Charlotte on Ice"
assert testclass.class.name == "de.myCorp.test.Test"
def usingclass = erg['using'].newInstance(testclass)
usingclass.mytest.a = "Fritzl"
assert usingclass.using() == "hello Fritzl"
...and especially notice the GroovyShell.evaluate(URI uri) types... GroovyShellDoc