Skip to content

Instantly share code, notes, and snippets.

@filipesperandio
Last active September 17, 2016 20:47
Show Gist options
  • Save filipesperandio/caeceb1f373446ddabfb to your computer and use it in GitHub Desktop.
Save filipesperandio/caeceb1f373446ddabfb to your computer and use it in GitHub Desktop.
Groovy construct child from parent
class Parent {
def fieldA
Map asMap() {
this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
["${it.name}": this[it.name]]
}
}
}
class Child extends Parent {
def fieldB
}
parent = new Parent(fieldA: "value")
child = parent.asMap() as Child
assert child.fieldA == parent.fieldA
assert child != parent
assert child instanceof Child
class Parent {
def fieldA
}
class Child extends Parent {
def fieldB
}
def att = parent.properties - parent.properties.subMap('class', 'metaClass')
new Child(att)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment