Skip to content

Instantly share code, notes, and snippets.

@ganta
Created Jul 20, 2013
Embed
What would you like to do?
MOP hands-on - JGGUG G* Workshop Z Jul 2013
String.metaClass.getLanguage = { "Groovy" }
String.metaClass.getLang = { "Groovy" }
assert "JGGUG".language == "Groovy"
assert "JGGUG".lang == "Groovy"
class Jggug {
def propertyMissing(String name, value) {
switch (name) {
case 'language':
case 'lang':
return 'Groovy'
default:
throw new MissingPropertyException(name, this.class)
}
}
}
assert new Jggug().language == "Groovy"
assert new Jggug().lang == "Groovy"
class Foo {
String bar() {
"@"
}
String piyo() {
"p"
}
def propertyMissing(String name, value) {
this."$name"()
}
}
assert new Foo().bar() == new Foo().bar
assert new Foo().piyo() == new Foo().piyo
import java.beans.Introspector
import java.util.regex.Matcher
class Someone {
def sexy = true
def cute = false
def propertyMissing(String name, value) {
switch (name) {
case ~/^isNot(.*)/:
case ~/^is(.*)/:
def propName = Introspector.decapitalize(Matcher.lastMatcher.group(1))
return this[propName] != name.startsWith('isNot')
default:
throw new MissingPropertyException(name, this.class)
}
}
}
assert new Someone().isSexy
assert !new Someone().isNotSexy
assert !new Someone().isCute
assert new Someone().isNotCute
import java.beans.Introspector
import java.util.regex.Matcher
class Somebody {
def sexy = true
def cute = false
def methodMissing(String name, args) {
switch (name) {
case ~/^isNot(.*)/:
case ~/^is(.*)/:
def propName = Introspector.decapitalize(Matcher.lastMatcher.group(1))
return this[propName] != name.startsWith('isNot')
default:
throw new MissingMethodException(name, this.class, args as Object[])
}
}
def propertyMissing(String name, value) {
if (name ==~ /not(.*)/) {
def propName = Introspector.decapitalize(Matcher.lastMatcher.group(1))
return !this[propName]
}
throw new MissingPropertyException(name, this.class)
}
}
assert new Somebody().isSexy()
assert !new Somebody().isNotSexy()
assert !new Somebody().isCute()
assert new Somebody().isNotCute()
assert new Somebody().sexy
assert !new Somebody().notSexy
assert !new Somebody().cute
assert new Somebody().notCute
import groovy.transform.Canonical
@Canonical
class Some {
int value
Some(int value) {
this.value = value
}
}
Class.metaClass.static.new = { Object[] args ->
delegate.newInstance(*args)
}
assert 123 == Integer.new(123)
assert new Some(123) == Some.new(123)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment