Skip to content

Instantly share code, notes, and snippets.

@int128
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int128/10742538 to your computer and use it in GitHub Desktop.
Save int128/10742538 to your computer and use it in GitHub Desktop.
Enumerate properties of an object using meta class
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]
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