Last active
September 17, 2016 20:47
-
-
Save filipesperandio/caeceb1f373446ddabfb to your computer and use it in GitHub Desktop.
Groovy construct child from parent
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
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 |
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
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