Last active
August 29, 2015 13:59
-
-
Save int128/10742538 to your computer and use it in GitHub Desktop.
Enumerate properties of an object using meta class
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 S { | |
def propertiesAsMap() { | |
this.metaClass.properties.collectEntries { p -> | |
[(p.name): p.modifiers] | |
} | |
} | |
} | |
class A extends S { | |
static int DEFAULT | |
int x | |
} | |
def a = new A() | |
a.propertiesAsMap() // -> [class:273, DEFAULT:9, x:1] |
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 S { | |
S plus(S s) { | |
def map = this.metaClass.properties.findAll { it.modifiers == 1 }.collectEntries { | |
[(it.name): (s[it.name] != null) ? s[it.name] : this[it.name]] | |
} | |
this.metaClass.invokeConstructor(map) | |
} | |
} | |
@groovy.transform.EqualsAndHashCode | |
@groovy.transform.ToString | |
class A extends S { | |
static final A DEFAULT = new A(x: 100, y: 200) | |
Integer x = null | |
Integer y = null | |
} | |
def a1 = new A(x: 10) | |
def a2 = new A(y: 20) | |
a1 + a2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment