SlideShare a Scribd company logo
1 of 116
Download to read offline
METAPROGRAMMING
WITH GROOVY
Iván López @ilopmar
Hello!
I am Iván López
@ilopmar
http://greachconf.com@madridgug
Groovy is dynamic
▷ “Delay” to runtime some decisions
▷ Add properties/behaviours in
runtime
▷ Wide range of applicability
What is
metaprogramming?
“Metaprogramming is the writing
of computer programs that write
or manipulate other programs (or
themselves) as their data.
- Wikipedia
1.
Runtime
metaprogramming
Runtime metaprogramming
▷ Groovy provides this through Meta-
Object Protocol (MOP)
▷ Use MOP to:
– Invoke methods dynamically
– Synthesize classes and methods on
the fly
What is the Meta Object Protocol?
Groovy
Groovy
Java
Java
MOP
Intercepting methods
using MOP
public interface GroovyObject {
Object invokeMethod(String name, Object args)
Object getProperty(String propertyName)
void setProperty(String propertyName, Object newValue)
MetaClass getMetaClass()
void setMetaClass(MetaClass metaClass)
}
Groovy Interceptable
▷ GroovyObject interface
▷ Implement GroovyInterceptable to hook
into the execution
GroovyInterceptable example
class Person implements GroovyInterceptable {
String name
Integer age
public Object getProperty(String propertyName) {
println "Getting property '${propertyName}'"
return this.@"${propertyName}"
}
public void setProperty(String propertyName, Object newValue) {
println "Setting property '${propertyName}' with value '${newValue}'"
this.@"${propertyName}" = newValue
}
}
def person = new Person()
person.name = "Iván"
person.age = 35
println "Hello ${person.name}, you're ${person.age}"
// Execution
Setting property 'name' with value 'Iván'
Setting property 'age' with value '35'
Getting property 'name'
Getting property 'age'
Hello Iván, you're 35
GroovyInterceptable example
class Person implements GroovyInterceptable {
String name
Integer age
public Object getProperty(String propertyName) {
println "Getting property '${propertyName}'"
return this.@"${propertyName}"
}
public void setProperty(String propertyName, Object newValue) {
println "Setting property '${propertyName}' with value '${newValue}'"
this.@"${propertyName}" = newValue
}
}
def person = new Person()
person.name = "Iván"
person.age = 35
println "Hello ${person.name}, you're ${person.age}"
// Execution
Setting property 'name' with value 'Iván'
Setting property 'age' with value '35'
Getting property 'name'
Getting property 'age'
Hello Iván, you're 35
GroovyInterceptable example
class Person implements GroovyInterceptable {
String name
Integer age
public Object getProperty(String propertyName) {
println "Getting property '${propertyName}'"
return this.@"${propertyName}"
}
public void setProperty(String propertyName, Object newValue) {
println "Setting property '${propertyName}' with value '${newValue}'"
this.@"${propertyName}" = newValue
}
}
def person = new Person()
person.name = "Iván"
person.age = 35
println "Hello ${person.name}, you're ${person.age}"
// Execution
Setting property 'name' with value 'Iván'
Setting property 'age' with value '35'
Getting property 'name'
Getting property 'age'
Hello Iván, you're 35
GroovyInterceptable example
class Person implements GroovyInterceptable {
String name
Integer age
public Object getProperty(String propertyName) {
println "Getting property '${propertyName}'"
return this.@"${propertyName}"
}
public void setProperty(String propertyName, Object newValue) {
println "Setting property '${propertyName}' with value '${newValue}'"
this.@"${propertyName}" = newValue
}
}
def person = new Person()
person.name = "Iván"
person.age = 35
println "Hello ${person.name}, you're ${person.age}"
// Execution
Setting property 'name' with value 'Iván'
Setting property 'age' with value '35'
Getting property 'name'
Getting property 'age'
Hello Iván, you're 35
GroovyInterceptable example
class Person implements GroovyInterceptable {
String name
Integer age
public Object getProperty(String propertyName) {
println "Getting property '${propertyName}'"
return this.@"${propertyName}"
}
public void setProperty(String propertyName, Object newValue) {
println "Setting property '${propertyName}' with value '${newValue}'"
this.@"${propertyName}" = newValue
}
}
def person = new Person()
person.name = "Iván"
person.age = 35
println "Hello ${person.name}, you're ${person.age}"
// Execution
Setting property 'name' with value 'Iván'
Setting property 'age' with value '35'
Getting property 'name'
Getting property 'age'
Hello Iván, you're 35
class Hello implements GroovyInterceptable {
public Object invokeMethod(String methodName, Object args) {
System.out.println "Invoking method '${methodName}' with args '${args}'"
def method = metaClass.getMetaMethod(methodName, args)
method?.invoke(this, args)
}
void sayHi(String name) {
System.out.println "Hello ${name}"
}
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
GroovyInterceptable example (II)
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
class Hello implements GroovyInterceptable {
public Object invokeMethod(String methodName, Object args) {
System.out.println "Invoking method '${methodName}' with args '${args}'"
def method = metaClass.getMetaMethod(methodName, args)
method?.invoke(this, args)
}
void sayHi(String name) {
System.out.println "Hello ${name}"
}
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
GroovyInterceptable example (II)
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
class Hello implements GroovyInterceptable {
public Object invokeMethod(String methodName, Object args) {
System.out.println "Invoking method '${methodName}' with args '${args}'"
def method = metaClass.getMetaMethod(methodName, args)
method?.invoke(this, args)
}
void sayHi(String name) {
System.out.println "Hello ${name}"
}
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
GroovyInterceptable example (II)
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
class Hello implements GroovyInterceptable {
public Object invokeMethod(String methodName, Object args) {
System.out.println "Invoking method '${methodName}' with args '${args}'"
def method = metaClass.getMetaMethod(methodName, args)
method?.invoke(this, args)
}
void sayHi(String name) {
System.out.println "Hello ${name}"
}
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
GroovyInterceptable example (II)
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
MetaClass
▷ MetaClass registry for each class
▷ Collection of methods/properties
▷ We can always modify the metaclass
▷ Intercept methods implementing
invokeMethod on metaclass
class Hello {
void sayHi(String name) {
println "Hello ${name}"
}
}
Hello.metaClass.invokeMethod = { String methodName, args ->
println "Invoking method '${methodName}' with args '${args}'"
def method = Hello.metaClass.getMetaMethod(methodName, args)
method?.invoke(delegate, args)
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
MetaClass example
class Hello {
void sayHi(String name) {
println "Hello ${name}"
}
}
Hello.metaClass.invokeMethod = { String methodName, args ->
println "Invoking method '${methodName}' with args '${args}'"
def method = Hello.metaClass.getMetaMethod(methodName, args)
method?.invoke(delegate, args)
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
MetaClass example
class Hello {
void sayHi(String name) {
println "Hello ${name}"
}
}
Hello.metaClass.invokeMethod = { String methodName, args ->
println "Invoking method '${methodName}' with args '${args}'"
def method = Hello.metaClass.getMetaMethod(methodName, args)
method?.invoke(delegate, args)
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
MetaClass example
class Hello {
void sayHi(String name) {
println "Hello ${name}"
}
}
Hello.metaClass.invokeMethod = { String methodName, args ->
println "Invoking method '${methodName}' with args '${args}'"
def method = Hello.metaClass.getMetaMethod(methodName, args)
method?.invoke(delegate, args)
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
MetaClass example
class Hello {
void sayHi(String name) {
println "Hello ${name}"
}
}
Hello.metaClass.invokeMethod = { String methodName, args ->
println "Invoking method '${methodName}' with args '${args}'"
def method = Hello.metaClass.getMetaMethod(methodName, args)
method?.invoke(delegate, args)
}
def hello = new Hello()
hello.sayHi("ConFess Vienna!")
hello.anotherMethod()
// Execution
Invoking method 'sayHi' with args '[ConFess Vienna!]'
Hello ConFess Vienna!
Invoking method 'anotherMethod' with args '[]'
MetaClass example
MOP method
injection
MOP Method Injection
▷ Injecting methods at code-writing time
▷ We can “open” a class any time
▷ Different techniques:
– MetaClass
– Categories
– Extensions
– Mixins vs Traits
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
// Execution
If you can see Chuck Norris, he can see you. If you can not see Chuck No
If you can see Chuck Norris, he can see you. If you can not see Chuck No...
String.metaClass.truncate = { Integer length, Boolean overflow = false ->
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true)
Adding methods using MetaClass
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
// Execution
If you can see Chuck Norris, he can see you. If you can not see Chuck No
If you can see Chuck Norris, he can see you. If you can not see Chuck No...
String.metaClass.truncate = { Integer length, Boolean overflow = false ->
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true)
Adding methods using MetaClass
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
// Execution
If you can see Chuck Norris, he can see you. If you can not see Chuck No
If you can see Chuck Norris, he can see you. If you can not see Chuck No...
String.metaClass.truncate = { Integer length, Boolean overflow = false ->
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true)
Adding methods using MetaClass
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
// Execution
If you can see Chuck Norris, he can see you. If you can not see Chuck No
If you can see Chuck Norris, he can see you. If you can not see Chuck No...
String.metaClass.truncate = { Integer length, Boolean overflow = false ->
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true)
Adding methods using MetaClass
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
// Execution
If you can see Chuck Norris, he can see you. If you can not see Chuck No
If you can see Chuck Norris, he can see you. If you can not see Chuck No...
String.metaClass.truncate = { Integer length, Boolean overflow = false ->
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true)
Adding methods using MetaClass
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
// Execution
If you can see Chuck Norris, he can see you. If you can not see Chuck No
If you can see Chuck Norris, he can see you. If you can not see Chuck No...
String.metaClass.truncate = { Integer length, Boolean overflow = false ->
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true)
Adding methods using MetaClass
class Utils {
}
def utilsInstance = new Utils()
Utils.metaClass.version = "3.0"
utilsInstance.metaClass.released = true
assert utilsInstance.version == "3.0"
assert utilsInstance.released == true
Adding properties using MetaClass
Adding properties using MetaClass
class Utils {
}
def utilsInstance = new Utils()
Utils.metaClass.version = "3.0"
utilsInstance.metaClass.released = true
assert utilsInstance.version == "3.0"
assert utilsInstance.released == true
class Utils {
}
def utilsInstance = new Utils()
Utils.metaClass.version = "3.0"
utilsInstance.metaClass.released = true
assert utilsInstance.version == "3.0"
assert utilsInstance.released == true
Adding properties using MetaClass
class Utils {
}
def utilsInstance = new Utils()
Utils.metaClass.version = "3.0"
utilsInstance.metaClass.released = true
assert utilsInstance.version == "3.0"
assert utilsInstance.released == true
Adding properties using MetaClass
// Integer
assert '42' == 42.toString()
Integer.metaClass.toString = {
delegate == 42 ?
'The answer to life, the universe and everything' :
String.valueOf(delegate)
}
assert 42.toString() == 'The answer to life, the universe and everything'
assert 100.toString() == '100'
// Boolean
assert false.toBoolean() == false
Boolean.metaClass.toBoolean = { !delegate }
assert false.toBoolean() == true
Overriding methods using MetaClass
// Integer
assert '42' == 42.toString()
Integer.metaClass.toString = {
delegate == 42 ?
'The answer to life, the universe and everything' :
String.valueOf(delegate)
}
assert 42.toString() == 'The answer to life, the universe and everything'
assert 100.toString() == '100'
// Boolean
assert false.toBoolean() == false
Boolean.metaClass.toBoolean = { !delegate }
assert false.toBoolean() == true
Overriding methods using MetaClass
// Integer
assert '42' == 42.toString()
Integer.metaClass.toString = {
delegate == 42 ?
'The answer to life, the universe and everything' :
String.valueOf(delegate)
}
assert 42.toString() == 'The answer to life, the universe and everything'
assert 100.toString() == '100'
// Boolean
assert false.toBoolean() == false
Boolean.metaClass.toBoolean = { !delegate }
assert false.toBoolean() == true
Overriding methods using MetaClass
// Integer
assert '42' == 42.toString()
Integer.metaClass.toString = {
delegate == 42 ?
'The answer to life, the universe and everything' :
String.valueOf(delegate)
}
assert 42.toString() == 'The answer to life, the universe and everything'
assert 100.toString() == '100'
// Boolean
assert false.toBoolean() == false
Boolean.metaClass.toBoolean = { !delegate }
assert false.toBoolean() == true
Overriding methods using MetaClass
// Integer
assert '42' == 42.toString()
Integer.metaClass.toString = {
delegate == 42 ?
'The answer to life, the universe and everything' :
String.valueOf(delegate)
}
assert 42.toString() == 'The answer to life, the universe and everything'
assert 100.toString() == '100'
// Boolean
assert false.toBoolean() == false
Boolean.metaClass.toBoolean = { !delegate }
assert false.toBoolean() == true
Overriding methods using MetaClass
// Integer
assert '42' == 42.toString()
Integer.metaClass.toString = {
delegate == 42 ?
'The answer to life, the universe and everything' :
String.valueOf(delegate)
}
assert 42.toString() == 'The answer to life, the universe and everything'
assert 100.toString() == '100'
// Boolean
assert false.toBoolean() == false
Boolean.metaClass.toBoolean = { !delegate }
assert false.toBoolean() == true
Overriding methods using MetaClass
Categories
▷ MetaClass changes are “persistent”
▷ Change metaclass in confined code
▷ MOP modified only in the closure
Categories example
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
use (StringUtils) {
println "Lorem ipsum".truncate(5)
}
try {
println "Lorem ipsum".truncate(5)
} catch (MissingMethodException mme) {
println mme
}
// Execution
Lorem
groovy.lang.MissingMethodException: No
signature of method:
java.lang.String.truncate() is
applicable for argument types:
(java.lang.Integer) values: [5]
Possible solutions:
concat(java.lang.String), take(int)
Categories example
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
use (StringUtils) {
println "Lorem ipsum".truncate(5)
}
try {
println "Lorem ipsum".truncate(5)
} catch (MissingMethodException mme) {
println mme
}
// Execution
Lorem
groovy.lang.MissingMethodException: No
signature of method:
java.lang.String.truncate() is
applicable for argument types:
(java.lang.Integer) values: [5]
Possible solutions:
concat(java.lang.String), take(int)
Categories example
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
use (StringUtils) {
println "Lorem ipsum".truncate(5)
}
try {
println "Lorem ipsum".truncate(5)
} catch (MissingMethodException mme) {
println mme
}
// Execution
Lorem
groovy.lang.MissingMethodException: No
signature of method:
java.lang.String.truncate() is
applicable for argument types:
(java.lang.Integer) values: [5]
Possible solutions:
concat(java.lang.String), take(int)
Categories example
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
use (StringUtils) {
println "Lorem ipsum".truncate(5)
}
try {
println "Lorem ipsum".truncate(5)
} catch (MissingMethodException mme) {
println mme
}
// Execution
Lorem
groovy.lang.MissingMethodException: No
signature of method:
java.lang.String.truncate() is
applicable for argument types:
(java.lang.Integer) values: [5]
Possible solutions:
concat(java.lang.String), take(int)
class FileBinaryCategory {
def static leftShift(File file, URL url) {
def input
def output
try {
input = url.openStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output << input
} finally {
input?.close()
output?.close()
}
}
}
Categories example (II)
class FileBinaryCategory {
def static leftShift(File file, URL url) {
def input
def output
try {
input = url.openStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output << input
} finally {
input?.close()
output?.close()
}
}
}
Categories example (II)
class FileBinaryCategory {
def static leftShift(File file, URL url) {
def input
def output
try {
input = url.openStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output << input
} finally {
input?.close()
output?.close()
}
}
}
Categories example (II)
File tmpFile = File.createTempFile('tmp_', '')
use (FileBinaryCategory) {
tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL()
}
println tmpFile
// Execution
/tmp/tmp_7428855173238452155
class FileBinaryCategory {
def static leftShift(File file, URL url) {
def input
def output
try {
input = url.openStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output << input
} finally {
input?.close()
output?.close()
}
}
}
Categories example (II)
File tmpFile = File.createTempFile('tmp_', '')
use (FileBinaryCategory) {
tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL()
}
println tmpFile
// Execution
/tmp/tmp_7428855173238452155
class FileBinaryCategory {
def static leftShift(File file, URL url) {
def input
def output
try {
input = url.openStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output << input
} finally {
input?.close()
output?.close()
}
}
}
Categories example (II)
File tmpFile = File.createTempFile('tmp_', '')
use (FileBinaryCategory) {
tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL()
}
println tmpFile
// Execution
/tmp/tmp_7428855173238452155
class FileBinaryCategory {
def static leftShift(File file, URL url) {
def input
def output
try {
input = url.openStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output << input
} finally {
input?.close()
output?.close()
}
}
}
Categories example (II)
File tmpFile = File.createTempFile('tmp_', '')
use (FileBinaryCategory) {
tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL()
}
println tmpFile
// Execution
/tmp/tmp_7428855173238452155
Extension modules
▷ JAR file that provides extra methods
▷ Meta-information file
▷ Put jar in classpath to enhance classes
// src/main/groovy/confess2015/StringUtilsExtension.groovy
package confess2015
class StringUtilsExtension {
static String truncate(String self, Integer length, Boolean overflow = false) {
self.take(length) + (overflow ? '...' : '')
}
}
package confess2015
import spock.lang.Specification
class StringUtilsExtensionSpec extends Specification {
void 'test trucate'() {
expect:
"Lorem" == "Lorem ipsum".truncate(5)
"Lorem..." == "Lorem ipsum".truncate(5, true)
}
}
// Execute with:
// gradle build
// groovy -cp build/libs/string-
extensions-1.0.jar
ExtensionExample1.groovy
assert "Lorem..." == "Lorem ipsum".
truncate(5, true)
# src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = string-utils-module
moduleVersion = 0.1
extensionClasses = confess2015.StringUtilsExtension
Extension modules example
Extension modules example
// src/main/groovy/confess2015/StringUtilsExtension.groovy
package confess2015
class StringUtilsExtension {
static String truncate(String self, Integer length, Boolean overflow = false) {
self.take(length) + (overflow ? '...' : '')
}
}
# src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = string-utils-module
moduleVersion = 0.1
extensionClasses = confess2015.StringUtilsExtension
package confess2015
import spock.lang.Specification
class StringUtilsExtensionSpec extends Specification {
void 'test trucate'() {
expect:
"Lorem" == "Lorem ipsum".truncate(5)
"Lorem..." == "Lorem ipsum".truncate(5, true)
}
}
// Execute with:
// gradle build
// groovy -cp build/libs/string-
extensions-1.0.jar
ExtensionExample1.groovy
assert "Lorem..." == "Lorem ipsum".
truncate(5, true)
Extension modules example
// src/main/groovy/confess2015/StringUtilsExtension.groovy
package confess2015
class StringUtilsExtension {
static String truncate(String self, Integer length, Boolean overflow = false) {
self.take(length) + (overflow ? '...' : '')
}
}
package confess2015
import spock.lang.Specification
class StringUtilsExtensionSpec extends Specification {
void 'test trucate'() {
expect:
"Lorem" == "Lorem ipsum".truncate(5)
"Lorem..." == "Lorem ipsum".truncate(5, true)
}
}
// Execute with:
// gradle build
// groovy -cp build/libs/string-
extensions-1.0.jar
ExtensionExample1.groovy
assert "Lorem..." == "Lorem ipsum".
truncate(5, true)
# src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = string-utils-module
moduleVersion = 0.1
extensionClasses = confess2015.StringUtilsExtension
Extension modules example
// src/main/groovy/confess2015/StringUtilsExtension.groovy
package confess2015
class StringUtilsExtension {
static String truncate(String self, Integer length, Boolean overflow = false) {
self.take(length) + (overflow ? '...' : '')
}
}
package confess2015
import spock.lang.Specification
class StringUtilsExtensionSpec extends Specification {
void 'test trucate'() {
expect:
"Lorem" == "Lorem ipsum".truncate(5)
"Lorem..." == "Lorem ipsum".truncate(5, true)
}
}
// Execute with:
// gradle build
// groovy -cp build/libs/string-
extensions-1.0.jar
ExtensionExample1.groovy
assert "Lorem..." == "Lorem ipsum".
truncate(5, true)
# src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = string-utils-module
moduleVersion = 0.1
extensionClasses = confess2015.StringUtilsExtension
// src/main/groovy/confess2015/StringUtilsExtension.groovy
package confess2015
class StringUtilsExtension {
static String truncate(String self, Integer length, Boolean overflow = false) {
self.take(length) + (overflow ? '...' : '')
}
}
package confess2015
import spock.lang.Specification
class StringUtilsExtensionSpec extends Specification {
void 'test trucate'() {
expect:
"Lorem" == "Lorem ipsum".truncate(5)
"Lorem..." == "Lorem ipsum".truncate(5, true)
}
}
// Execute with:
// gradle build
// groovy -cp build/libs/string-
extensions-1.0.jar
ExtensionExample1.groovy
assert "Lorem..." == "Lorem ipsum".
truncate(5, true)
Extension modules example
# src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = string-utils-module
moduleVersion = 0.1
extensionClasses = confess2015.StringUtilsExtension
Mixins
▷ “Bring in” or “mix in” implementations
from multiple classes
▷ Calls first routed to mixed-in class
▷ Last mixin wins
▷ Not easily un-done
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
Mixins example
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
class SupermanPower {
String fly() {
"Flying..."
}
}
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
class SupermanPower {
String fly() {
"Flying..."
}
}
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
Mixins example
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
class SupermanPower {
String fly() {
"Flying..."
}
}
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
Mixins example
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
class SupermanPower {
String fly() {
"Flying..."
}
}
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
Mixins example
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
Mixins example
class SupermanPower {
String fly() {
"Flying..."
}
}
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
Mixins example
class SupermanPower {
String fly() {
"Flying..."
}
}
Traits
▷ Groovy 2.3+
▷ Similar to Java 8 default methods
▷ Supported in JDK 6, 7 and 8
▷ Stateful
▷ Composition over inheritance
▷ Documentation
class Person implements SpidermanPower {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert person instanceof SpidermanPower
def person2 = person.withTraits SupermanPower
assert person2.fly() == "Flying..."
assert person2 instanceof SupermanPower
Traits example
trait SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
trait SupermanPower {
String fly() {
"Flying..."
}
}
class Person implements SpidermanPower {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert person instanceof SpidermanPower
def person2 = person.withTraits SupermanPower
assert person2.fly() == "Flying..."
assert person2 instanceof SupermanPower
Traits example
trait SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
trait SupermanPower {
String fly() {
"Flying..."
}
}
class Person implements SpidermanPower {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert person instanceof SpidermanPower
def person2 = person.withTraits SupermanPower
assert person2.fly() == "Flying..."
assert person2 instanceof SupermanPower
Traits example
trait SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
trait SupermanPower {
String fly() {
"Flying..."
}
}
class Person implements SpidermanPower {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert person instanceof SpidermanPower
def person2 = person.withTraits SupermanPower
assert person2.fly() == "Flying..."
assert person2 instanceof SupermanPower
Traits example
trait SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
trait SupermanPower {
String fly() {
"Flying..."
}
}
MOP method
synthesis
MOP Method Synthesis
▷ Dynamically figure out behaviour upon
invocation
▷ It may not exist until it's called/executed
▷ “Intercept, Cache, Invoke” pattern
def p = new Person(name: 'Iván', age: 34)
assert p.respondsTo('sayHi')
assert p.respondsTo('sayHiTo', String)
assert !p.respondsTo('goodbye')
assert p.hasProperty('name')
assert !p.hasProperty('country')
Check for methods and properties
class Person {
String name
Integer age
String sayHi() {
"Hi, my name is ${name} and I'm ${age}"
}
String sayHiTo(String name) {
"Hi ${name}, how are you?"
}
}
def p = new Person(name: 'Iván', age: 35)
assert p.respondsTo('sayHi')
assert p.respondsTo('sayHiTo', String)
assert !p.respondsTo('goodbye')
assert p.hasProperty('age')
assert !p.hasProperty('country')
Check for methods and properties
class Person {
String name
Integer age
String sayHi() {
"Hi, my name is ${name} and I'm ${age}"
}
String sayHiTo(String name) {
"Hi ${name}, how are you?"
}
}
Check for methods and properties
class Person {
String name
Integer age
String sayHi() {
"Hi, my name is ${name} and I'm ${age}"
}
String sayHiTo(String name) {
"Hi ${name}, how are you?"
}
}
def p = new Person(name: 'Iván', age: 35)
assert p.respondsTo('sayHi')
assert p.respondsTo('sayHiTo', String)
assert !p.respondsTo('goodbye')
assert p.hasProperty('age')
assert !p.hasProperty('country')
Check for methods and properties
class Person {
String name
Integer age
String sayHi() {
"Hi, my name is ${name} and I'm ${age}"
}
String sayHiTo(String name) {
"Hi ${name}, how are you?"
}
}
def p = new Person(name: 'Iván', age: 35)
assert p.respondsTo('sayHi')
assert p.respondsTo('sayHiTo', String)
assert !p.respondsTo('goodbye')
assert p.hasProperty('age')
assert !p.hasProperty('country')
MethodMissing example
▷ Requirements:
– Send notifications to users by different
channels
– +50 notifications
– Not all notifications by all channels
– Extensible and open to future
modifications
MethodMissing example
abstract class Channel {
void sendNewFollower(String username, String follower) { }
void sendNewMessage(String username, String msg) { }
...
}
class EmailChannel extends Channel {
void sendNewFollower(String username, String follower) {
println "Sending email notification to '${username}' for new follower '${follower}'"
}
void sendNewMessage(String username, String msg) {
println "Sending email notification to '${username}' for new message '${msg}'"
}
}
class MobilePushChannel extends Channel {
void sendNewFollower(String username, String follower) {
println "Sending mobile push notification to '${username}' for new follower '${follower}'"
}
}
MethodMissing example
abstract class Channel {
void sendNewFollower(String username, String follower) { }
void sendNewMessage(String username, String msg) { }
...
}
class EmailChannel extends Channel {
void sendNewFollower(String username, String follower) {
println "Sending email notification to '${username}' for new follower '${follower}'"
}
void sendNewMessage(String username, String msg) {
println "Sending email notification to '${username}' for new message '${msg}'"
}
}
class MobilePushChannel extends Channel {
void sendNewFollower(String username, String follower) {
println "Sending mobile push notification to '${username}' for new follower '${follower}'"
}
}
MethodMissing example
abstract class Channel {
void sendNewFollower(String username, String follower) { }
void sendNewMessage(String username, String msg) { }
...
}
class EmailChannel extends Channel {
void sendNewFollower(String username, String follower) {
println "Sending email notification to '${username}' for new follower '${follower}'"
}
void sendNewMessage(String username, String msg) {
println "Sending email notification to '${username}' for new message '${msg}'"
}
}
class MobilePushChannel extends Channel {
void sendNewFollower(String username, String follower) {
println "Sending mobile push notification to '${username}' for new follower '${follower}'"
}
}
MethodMissing example
class NotificationService {
List channels = []
def methodMissing(String name, args) {
System.out.println "...methodMissing called for ${name} with args ${args}"
// Generate the implementation
def implementation = { Object[] methodArgs ->
channels.each { channel ->
def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs)
return metaMethod.invoke(channel, methodArgs)
}
}
// Cache the implementation in the metaClass
NotificationService instance = this
instance.metaClass."$name" = implementation
// Execute it!
implementation(args)
}
}
MethodMissing example
class NotificationService {
List channels = []
def methodMissing(String name, args) {
System.out.println "...methodMissing called for ${name} with args ${args}"
// Generate the implementation
def implementation = { Object[] methodArgs ->
channels.each { channel ->
def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs)
return metaMethod.invoke(channel, methodArgs)
}
}
// Cache the implementation in the metaClass
NotificationService instance = this
instance.metaClass."$name" = implementation
// Execute it!
implementation(args)
}
}
MethodMissing example
class NotificationService {
List channels = []
def methodMissing(String name, args) {
System.out.println "...methodMissing called for ${name} with args ${args}"
// Generate the implementation
def implementation = { Object[] methodArgs ->
channels.each { channel ->
def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs)
return metaMethod.invoke(channel, methodArgs)
}
}
// Cache the implementation in the metaClass
NotificationService instance = this
instance.metaClass."$name" = implementation
// Execute it!
implementation(args)
}
}
notificationService.sendNewFollower(...)
notificationService.sendNewMessage(...)
MethodMissing example
class NotificationService {
List channels = []
def methodMissing(String name, args) {
System.out.println "...methodMissing called for ${name} with args ${args}"
// Generate the implementation
def implementation = { Object[] methodArgs ->
channels.each { channel ->
def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs)
return metaMethod.invoke(channel, methodArgs)
}
}
// Cache the implementation in the metaClass
NotificationService instance = this
instance.metaClass."$name" = implementation
// Execute it!
implementation(args)
}
}
MethodMissing example
class NotificationService {
List channels = []
def methodMissing(String name, args) {
System.out.println "...methodMissing called for ${name} with args ${args}"
// Generate the implementation
def implementation = { Object[] methodArgs ->
channels.each { channel ->
def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs)
return metaMethod.invoke(channel, methodArgs)
}
}
// Cache the implementation in the metaClass
NotificationService instance = this
instance.metaClass."$name" = implementation
// Execute it!
implementation(args)
}
}
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")class EmailChannel extends Channel {
void sendNewFollower(String username, String follower) {…}
void sendNewMessage(String username, String msg) {…}
}
class MobilePushChannel extends Channel {
void sendNewFollower(String username, String follower) {…}
}
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
MethodMissing example
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
MethodMissing example
def notificationService = new NotificationService(
channels: [new EmailChannel(), new MobilePushChannel()]
)
assert !notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("John", "Peter")
assert notificationService.respondsTo('sendNewFollower', String, String)
notificationService.sendNewFollower("Mary", "Steve")
notificationService.sendNewMessage("Iván", "Hello!")
// Execution
...methodMissing called for sendNewFollower with args [John, Peter]
Sending email notification to 'John' for new follower 'Peter'
Sending mobile push notification to 'John' for new follower 'Peter'
Sending email notification to 'Mary' for new follower 'Steve'
Sending mobile push notification to 'Mary' for new follower 'Steve'
...methodMissing called for sendNewMessage with args [Iván, Hello!]
Sending email notification to 'Iván' for new message 'Hello!'
2.
Compile-time
metaprogramming
Compile-time metaprogramming
▷ Advance feature
▷ Analyze/modify program structure at
compile time
▷ Cross-cutting features
▷ Write code that generates bytecode
AST and compilation
▷ AST: Abstract Syntax Tree
▷ AST modified during compilation
▷ Hook into the phases
▷ Initialization, Parsing, Conversion,
Semantic analysis, Canonicalization,
Instruction selection, Class
generation, Output, Finalization
Global AST
transformations
Global AST Transformations
▷ No annotation
▷ Meta-information file
▷ Applied to all code during compilation
▷ Any compilation phase
▷ Grails uses intensively in GORM
Local AST
transformations
Local AST Transformations
▷ Annotate code
▷ No meta-information file
▷ Easy to debug
Steps to create local AST
Interface AST Enjoy!
Local AST example
package confess2015
import ...
@Retention(RetentionPolicy.SOURCE)
@Target([ElementType.TYPE])
@GroovyASTTransformationClass("confess2015.VersionASTTransformation")
@interface Version {
String value()
}
class VersionedClass {
public static final String VERSION = "1.0"
}
import confess2015.Version
@Version('1.0')
class VersionedClass {
}
Local AST example
class VersionedClass {
public static final String VERSION = "1.0"
}
package confess2015
import ...
@Retention(RetentionPolicy.SOURCE)
@Target([ElementType.TYPE])
@GroovyASTTransformationClass("confess2015.VersionASTTransformation")
@interface Version {
String value()
}
import confess2015.Version
@Version('1.0')
class VersionedClass {
}
Local AST example
class VersionedClass {
public static final String VERSION = "1.0"
}
package confess2015
import ...
@Retention(RetentionPolicy.SOURCE)
@Target([ElementType.TYPE])
@GroovyASTTransformationClass("confess2015.VersionASTTransformation")
@interface Version {
String value()
}
import confess2015.Version
@Version('1.0')
class VersionedClass {
}
Local AST example
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class VersionASTTransformation extends AbstractASTTransformation {
@Override
public void visit(final ASTNode[] nodes, final SourceUnit source) {
if (nodes.length != 2) {
return
}
if (nodes[0] instanceof AnnotationNode && nodes[1] instanceof ClassNode) {
def annotation = nodes[0]
def version = annotation.getMember('value')
if (version instanceof ConstantExpression) {
nodes[1].addField('VERSION', ACC_PUBLIC | ACC_STATIC | ACC_FINAL,
ClassHelper.STRING_TYPE, version)
} else {
source.addError(new SyntaxException("Invalid value for annotation", annotation.lineNumber,
annotation.columnNumber))
}
}
}
}
Local AST example
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class VersionASTTransformation extends AbstractASTTransformation {
@Override
public void visit(final ASTNode[] nodes, final SourceUnit source) {
if (nodes.length != 2) {
return
}
if (nodes[0] instanceof AnnotationNode && nodes[1] instanceof ClassNode) {
def annotation = nodes[0]
def version = annotation.getMember('value')
if (version instanceof ConstantExpression) {
nodes[1].addField('VERSION', ACC_PUBLIC | ACC_STATIC | ACC_FINAL,
ClassHelper.STRING_TYPE, version)
} else {
source.addError(new SyntaxException("Invalid value for annotation", annotation.lineNumber,
annotation.columnNumber))
}
}
}
}
Local AST example
// Execute with:
// gradle build
// groovy -cp build/libs/add-version-1.0.jar LocalASTExample.groovy
import confess.Version
@Version('1.0')
class VersionedClass {
}
println VersionedClass.VERSION
// Execution
1.0
Local AST example
// Execute with:
// gradle build
// groovy -cp build/libs/add-version-1.0.jar LocalASTExample.groovy
import confess.Version
@Version('1.0')
class VersionedClass {
}
println VersionedClass.VERSION
// Execution
1.0
Local AST example
// Execute with:
// gradle build
// groovy -cp build/libs/add-version-1.0.jar LocalASTExample.groovy
import confess.Version
@Version('1.0')
class VersionedClass {
}
println VersionedClass.VERSION
// Execution
1.0
3.
Why we should use
metaprogramming?
Let’s review some concepts
Metaprogramming
out-of-the box
Easy and very
powerful
Write better code
Add behaviour
easily
Take advantage of
this power
Because Groovy,
it's groovy
With great power
comes great
responsibility
Thanks!
Any questions?
@ilopmar
lopez.ivan@gmail.com
https://github.com/lmivan
Iván López
http://kcy.me/208wq
ConFess Vienna 2015 - Metaprogramming with Groovy

More Related Content

What's hot

Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Guillaume Laforge
 
AST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres AlmirayAST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres AlmirayZeroTurnaround
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Chang W. Doh
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Phil Calçado
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...Phil Calçado
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 

What's hot (20)

Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013
 
AST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres AlmirayAST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres Almiray
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
Groovy 2.0 webinar
Groovy 2.0 webinarGroovy 2.0 webinar
Groovy 2.0 webinar
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
Groovy!
Groovy!Groovy!
Groovy!
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Ggug spock
Ggug spockGgug spock
Ggug spock
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 

Viewers also liked

RigaDevDay 2016 - Testing with Spock: The Logical Choice
RigaDevDay 2016 - Testing with Spock: The Logical ChoiceRigaDevDay 2016 - Testing with Spock: The Logical Choice
RigaDevDay 2016 - Testing with Spock: The Logical ChoiceIván López Martín
 
ConFoo 2016 - Mum, I want to be a Groovy full-stack developer
ConFoo 2016 - Mum, I want to be a Groovy full-stack developerConFoo 2016 - Mum, I want to be a Groovy full-stack developer
ConFoo 2016 - Mum, I want to be a Groovy full-stack developerIván López Martín
 
London-GGUG 2015 - Metaprogramming Options with Groovy
London-GGUG 2015 - Metaprogramming Options with GroovyLondon-GGUG 2015 - Metaprogramming Options with Groovy
London-GGUG 2015 - Metaprogramming Options with GroovyIván López Martín
 
GeeCON Krakow 2015 - Grails and the real-time world
GeeCON Krakow 2015 - Grails and the real-time worldGeeCON Krakow 2015 - Grails and the real-time world
GeeCON Krakow 2015 - Grails and the real-time worldIván López Martín
 
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Iván López Martín
 
ConFoo 2016 - Metaprogramming with Groovy
ConFoo 2016 - Metaprogramming with GroovyConFoo 2016 - Metaprogramming with Groovy
ConFoo 2016 - Metaprogramming with GroovyIván López Martín
 
Spring I/O 2015 - Mum, I want to be a Groovy full-stack developer
Spring I/O 2015 - Mum, I want to be a Groovy full-stack developerSpring I/O 2015 - Mum, I want to be a Groovy full-stack developer
Spring I/O 2015 - Mum, I want to be a Groovy full-stack developerIván López Martín
 
GR8Conf 2016 - Metaprogramming with Groovy
GR8Conf 2016 - Metaprogramming with GroovyGR8Conf 2016 - Metaprogramming with Groovy
GR8Conf 2016 - Metaprogramming with GroovyIván López Martín
 
SpringOne 2GX 2015 - Fullstack Groovy developer
SpringOne 2GX 2015 - Fullstack Groovy developerSpringOne 2GX 2015 - Fullstack Groovy developer
SpringOne 2GX 2015 - Fullstack Groovy developerIván López Martín
 
JavaCro 2016 - Testing with Spock: The Logical choice
JavaCro 2016 - Testing with Spock: The Logical choiceJavaCro 2016 - Testing with Spock: The Logical choice
JavaCro 2016 - Testing with Spock: The Logical choiceIván López Martín
 
JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!Iván López Martín
 
VirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceVirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceIván López Martín
 

Viewers also liked (13)

RigaDevDay 2016 - Testing with Spock: The Logical Choice
RigaDevDay 2016 - Testing with Spock: The Logical ChoiceRigaDevDay 2016 - Testing with Spock: The Logical Choice
RigaDevDay 2016 - Testing with Spock: The Logical Choice
 
ConFoo 2016 - Mum, I want to be a Groovy full-stack developer
ConFoo 2016 - Mum, I want to be a Groovy full-stack developerConFoo 2016 - Mum, I want to be a Groovy full-stack developer
ConFoo 2016 - Mum, I want to be a Groovy full-stack developer
 
London-GGUG 2015 - Metaprogramming Options with Groovy
London-GGUG 2015 - Metaprogramming Options with GroovyLondon-GGUG 2015 - Metaprogramming Options with Groovy
London-GGUG 2015 - Metaprogramming Options with Groovy
 
GeeCON Krakow 2015 - Grails and the real-time world
GeeCON Krakow 2015 - Grails and the real-time worldGeeCON Krakow 2015 - Grails and the real-time world
GeeCON Krakow 2015 - Grails and the real-time world
 
Greach 2016 dockerize your grails
Greach 2016   dockerize your grailsGreach 2016   dockerize your grails
Greach 2016 dockerize your grails
 
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
 
ConFoo 2016 - Metaprogramming with Groovy
ConFoo 2016 - Metaprogramming with GroovyConFoo 2016 - Metaprogramming with Groovy
ConFoo 2016 - Metaprogramming with Groovy
 
Spring I/O 2015 - Mum, I want to be a Groovy full-stack developer
Spring I/O 2015 - Mum, I want to be a Groovy full-stack developerSpring I/O 2015 - Mum, I want to be a Groovy full-stack developer
Spring I/O 2015 - Mum, I want to be a Groovy full-stack developer
 
GR8Conf 2016 - Metaprogramming with Groovy
GR8Conf 2016 - Metaprogramming with GroovyGR8Conf 2016 - Metaprogramming with Groovy
GR8Conf 2016 - Metaprogramming with Groovy
 
SpringOne 2GX 2015 - Fullstack Groovy developer
SpringOne 2GX 2015 - Fullstack Groovy developerSpringOne 2GX 2015 - Fullstack Groovy developer
SpringOne 2GX 2015 - Fullstack Groovy developer
 
JavaCro 2016 - Testing with Spock: The Logical choice
JavaCro 2016 - Testing with Spock: The Logical choiceJavaCro 2016 - Testing with Spock: The Logical choice
JavaCro 2016 - Testing with Spock: The Logical choice
 
JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!
 
VirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceVirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choice
 

Similar to ConFess Vienna 2015 - Metaprogramming with Groovy

GeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyGeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyIván López Martín
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークTsuyoshi Yamamoto
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx WorkshopDierk König
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailszenMonkey
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developersPuneet Behl
 
Groovy And Grails JUG Padova
Groovy And Grails JUG PadovaGroovy And Grails JUG Padova
Groovy And Grails JUG PadovaJohn Leach
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module DevelopmentJay Harris
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle GroovyDeepak Bhagat
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?Chang W. Doh
 
Grails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitGrails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitZachary Klein
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaJohn Leach
 

Similar to ConFess Vienna 2015 - Metaprogramming with Groovy (20)

GeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyGeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with Groovy
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx Workshop
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And Grails
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
 
Groovy And Grails JUG Padova
Groovy And Grails JUG PadovaGroovy And Grails JUG Padova
Groovy And Grails JUG Padova
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module Development
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?
 
Grails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitGrails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to Orbit
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
 

More from Iván López Martín

SalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 TestcontainersSalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 TestcontainersIván López Martín
 
CommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 TestcontainersCommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 TestcontainersIván López Martín
 
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdfVoxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdfIván López Martín
 
VMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring BootVMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring BootIván López Martín
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewayIván López Martín
 
Codemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootCodemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootIván López Martín
 
CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3Iván López Martín
 
Construyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVMConstruyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVMIván López Martín
 
jLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTjLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTIván López Martín
 
Codemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con MicronautCodemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con MicronautIván López Martín
 
JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!Iván López Martín
 
JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3Iván López Martín
 
JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3Iván López Martín
 
Developing Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEADeveloping Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEAIván López Martín
 
CommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfectaCommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfectaIván López Martín
 
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!Iván López Martín
 
Greach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut ConfigurationsGreach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut ConfigurationsIván López Martín
 
VoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet youVoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet youIván López Martín
 
JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!Iván López Martín
 
CrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerteCrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerteIván López Martín
 

More from Iván López Martín (20)

SalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 TestcontainersSalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 Testcontainers
 
CommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 TestcontainersCommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 Testcontainers
 
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdfVoxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
 
VMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring BootVMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring Boot
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
 
Codemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootCodemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring Boot
 
CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3
 
Construyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVMConstruyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVM
 
jLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTjLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoT
 
Codemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con MicronautCodemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con Micronaut
 
JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!
 
JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3
 
JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3
 
Developing Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEADeveloping Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEA
 
CommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfectaCommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
 
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
 
Greach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut ConfigurationsGreach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut Configurations
 
VoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet youVoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet you
 
JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!
 
CrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerteCrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerte
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

ConFess Vienna 2015 - Metaprogramming with Groovy

  • 2. Hello! I am Iván López @ilopmar http://greachconf.com@madridgug
  • 3. Groovy is dynamic ▷ “Delay” to runtime some decisions ▷ Add properties/behaviours in runtime ▷ Wide range of applicability
  • 5. “Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data. - Wikipedia
  • 7. Runtime metaprogramming ▷ Groovy provides this through Meta- Object Protocol (MOP) ▷ Use MOP to: – Invoke methods dynamically – Synthesize classes and methods on the fly
  • 8. What is the Meta Object Protocol? Groovy Groovy Java Java MOP
  • 10. public interface GroovyObject { Object invokeMethod(String name, Object args) Object getProperty(String propertyName) void setProperty(String propertyName, Object newValue) MetaClass getMetaClass() void setMetaClass(MetaClass metaClass) } Groovy Interceptable ▷ GroovyObject interface ▷ Implement GroovyInterceptable to hook into the execution
  • 11. GroovyInterceptable example class Person implements GroovyInterceptable { String name Integer age public Object getProperty(String propertyName) { println "Getting property '${propertyName}'" return this.@"${propertyName}" } public void setProperty(String propertyName, Object newValue) { println "Setting property '${propertyName}' with value '${newValue}'" this.@"${propertyName}" = newValue } } def person = new Person() person.name = "Iván" person.age = 35 println "Hello ${person.name}, you're ${person.age}" // Execution Setting property 'name' with value 'Iván' Setting property 'age' with value '35' Getting property 'name' Getting property 'age' Hello Iván, you're 35
  • 12. GroovyInterceptable example class Person implements GroovyInterceptable { String name Integer age public Object getProperty(String propertyName) { println "Getting property '${propertyName}'" return this.@"${propertyName}" } public void setProperty(String propertyName, Object newValue) { println "Setting property '${propertyName}' with value '${newValue}'" this.@"${propertyName}" = newValue } } def person = new Person() person.name = "Iván" person.age = 35 println "Hello ${person.name}, you're ${person.age}" // Execution Setting property 'name' with value 'Iván' Setting property 'age' with value '35' Getting property 'name' Getting property 'age' Hello Iván, you're 35
  • 13. GroovyInterceptable example class Person implements GroovyInterceptable { String name Integer age public Object getProperty(String propertyName) { println "Getting property '${propertyName}'" return this.@"${propertyName}" } public void setProperty(String propertyName, Object newValue) { println "Setting property '${propertyName}' with value '${newValue}'" this.@"${propertyName}" = newValue } } def person = new Person() person.name = "Iván" person.age = 35 println "Hello ${person.name}, you're ${person.age}" // Execution Setting property 'name' with value 'Iván' Setting property 'age' with value '35' Getting property 'name' Getting property 'age' Hello Iván, you're 35
  • 14. GroovyInterceptable example class Person implements GroovyInterceptable { String name Integer age public Object getProperty(String propertyName) { println "Getting property '${propertyName}'" return this.@"${propertyName}" } public void setProperty(String propertyName, Object newValue) { println "Setting property '${propertyName}' with value '${newValue}'" this.@"${propertyName}" = newValue } } def person = new Person() person.name = "Iván" person.age = 35 println "Hello ${person.name}, you're ${person.age}" // Execution Setting property 'name' with value 'Iván' Setting property 'age' with value '35' Getting property 'name' Getting property 'age' Hello Iván, you're 35
  • 15. GroovyInterceptable example class Person implements GroovyInterceptable { String name Integer age public Object getProperty(String propertyName) { println "Getting property '${propertyName}'" return this.@"${propertyName}" } public void setProperty(String propertyName, Object newValue) { println "Setting property '${propertyName}' with value '${newValue}'" this.@"${propertyName}" = newValue } } def person = new Person() person.name = "Iván" person.age = 35 println "Hello ${person.name}, you're ${person.age}" // Execution Setting property 'name' with value 'Iván' Setting property 'age' with value '35' Getting property 'name' Getting property 'age' Hello Iván, you're 35
  • 16. class Hello implements GroovyInterceptable { public Object invokeMethod(String methodName, Object args) { System.out.println "Invoking method '${methodName}' with args '${args}'" def method = metaClass.getMetaMethod(methodName, args) method?.invoke(this, args) } void sayHi(String name) { System.out.println "Hello ${name}" } } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() GroovyInterceptable example (II) // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]'
  • 17. class Hello implements GroovyInterceptable { public Object invokeMethod(String methodName, Object args) { System.out.println "Invoking method '${methodName}' with args '${args}'" def method = metaClass.getMetaMethod(methodName, args) method?.invoke(this, args) } void sayHi(String name) { System.out.println "Hello ${name}" } } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() GroovyInterceptable example (II) // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]'
  • 18. class Hello implements GroovyInterceptable { public Object invokeMethod(String methodName, Object args) { System.out.println "Invoking method '${methodName}' with args '${args}'" def method = metaClass.getMetaMethod(methodName, args) method?.invoke(this, args) } void sayHi(String name) { System.out.println "Hello ${name}" } } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() GroovyInterceptable example (II) // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]'
  • 19. class Hello implements GroovyInterceptable { public Object invokeMethod(String methodName, Object args) { System.out.println "Invoking method '${methodName}' with args '${args}'" def method = metaClass.getMetaMethod(methodName, args) method?.invoke(this, args) } void sayHi(String name) { System.out.println "Hello ${name}" } } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() GroovyInterceptable example (II) // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]'
  • 20. MetaClass ▷ MetaClass registry for each class ▷ Collection of methods/properties ▷ We can always modify the metaclass ▷ Intercept methods implementing invokeMethod on metaclass
  • 21. class Hello { void sayHi(String name) { println "Hello ${name}" } } Hello.metaClass.invokeMethod = { String methodName, args -> println "Invoking method '${methodName}' with args '${args}'" def method = Hello.metaClass.getMetaMethod(methodName, args) method?.invoke(delegate, args) } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]' MetaClass example
  • 22. class Hello { void sayHi(String name) { println "Hello ${name}" } } Hello.metaClass.invokeMethod = { String methodName, args -> println "Invoking method '${methodName}' with args '${args}'" def method = Hello.metaClass.getMetaMethod(methodName, args) method?.invoke(delegate, args) } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]' MetaClass example
  • 23. class Hello { void sayHi(String name) { println "Hello ${name}" } } Hello.metaClass.invokeMethod = { String methodName, args -> println "Invoking method '${methodName}' with args '${args}'" def method = Hello.metaClass.getMetaMethod(methodName, args) method?.invoke(delegate, args) } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]' MetaClass example
  • 24. class Hello { void sayHi(String name) { println "Hello ${name}" } } Hello.metaClass.invokeMethod = { String methodName, args -> println "Invoking method '${methodName}' with args '${args}'" def method = Hello.metaClass.getMetaMethod(methodName, args) method?.invoke(delegate, args) } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]' MetaClass example
  • 25. class Hello { void sayHi(String name) { println "Hello ${name}" } } Hello.metaClass.invokeMethod = { String methodName, args -> println "Invoking method '${methodName}' with args '${args}'" def method = Hello.metaClass.getMetaMethod(methodName, args) method?.invoke(delegate, args) } def hello = new Hello() hello.sayHi("ConFess Vienna!") hello.anotherMethod() // Execution Invoking method 'sayHi' with args '[ConFess Vienna!]' Hello ConFess Vienna! Invoking method 'anotherMethod' with args '[]' MetaClass example
  • 27. MOP Method Injection ▷ Injecting methods at code-writing time ▷ We can “open” a class any time ▷ Different techniques: – MetaClass – Categories – Extensions – Mixins vs Traits
  • 28. class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } String chuckIpsum = "If you can see Chuck Norris, he can see you. If you can not see Chuck Norris you may be only seconds away from death" println StringUtils.truncate(chuckIpsum, 72) println StringUtils.truncate(chuckIpsum, 72, true) // Execution If you can see Chuck Norris, he can see you. If you can not see Chuck No If you can see Chuck Norris, he can see you. If you can not see Chuck No... String.metaClass.truncate = { Integer length, Boolean overflow = false -> delegate.take(length) + (overflow ? '...' : '') } assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true) Adding methods using MetaClass
  • 29. class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } String chuckIpsum = "If you can see Chuck Norris, he can see you. If you can not see Chuck Norris you may be only seconds away from death" println StringUtils.truncate(chuckIpsum, 72) println StringUtils.truncate(chuckIpsum, 72, true) // Execution If you can see Chuck Norris, he can see you. If you can not see Chuck No If you can see Chuck Norris, he can see you. If you can not see Chuck No... String.metaClass.truncate = { Integer length, Boolean overflow = false -> delegate.take(length) + (overflow ? '...' : '') } assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true) Adding methods using MetaClass
  • 30. class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } String chuckIpsum = "If you can see Chuck Norris, he can see you. If you can not see Chuck Norris you may be only seconds away from death" println StringUtils.truncate(chuckIpsum, 72) println StringUtils.truncate(chuckIpsum, 72, true) // Execution If you can see Chuck Norris, he can see you. If you can not see Chuck No If you can see Chuck Norris, he can see you. If you can not see Chuck No... String.metaClass.truncate = { Integer length, Boolean overflow = false -> delegate.take(length) + (overflow ? '...' : '') } assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true) Adding methods using MetaClass
  • 31. class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } String chuckIpsum = "If you can see Chuck Norris, he can see you. If you can not see Chuck Norris you may be only seconds away from death" println StringUtils.truncate(chuckIpsum, 72) println StringUtils.truncate(chuckIpsum, 72, true) // Execution If you can see Chuck Norris, he can see you. If you can not see Chuck No If you can see Chuck Norris, he can see you. If you can not see Chuck No... String.metaClass.truncate = { Integer length, Boolean overflow = false -> delegate.take(length) + (overflow ? '...' : '') } assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true) Adding methods using MetaClass
  • 32. class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } String chuckIpsum = "If you can see Chuck Norris, he can see you. If you can not see Chuck Norris you may be only seconds away from death" println StringUtils.truncate(chuckIpsum, 72) println StringUtils.truncate(chuckIpsum, 72, true) // Execution If you can see Chuck Norris, he can see you. If you can not see Chuck No If you can see Chuck Norris, he can see you. If you can not see Chuck No... String.metaClass.truncate = { Integer length, Boolean overflow = false -> delegate.take(length) + (overflow ? '...' : '') } assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true) Adding methods using MetaClass
  • 33. class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } String chuckIpsum = "If you can see Chuck Norris, he can see you. If you can not see Chuck Norris you may be only seconds away from death" println StringUtils.truncate(chuckIpsum, 72) println StringUtils.truncate(chuckIpsum, 72, true) // Execution If you can see Chuck Norris, he can see you. If you can not see Chuck No If you can see Chuck Norris, he can see you. If you can not see Chuck No... String.metaClass.truncate = { Integer length, Boolean overflow = false -> delegate.take(length) + (overflow ? '...' : '') } assert chuckIpsum.truncate(72, true) == StringUtils.truncate(chuckIpsum, 72, true) Adding methods using MetaClass
  • 34. class Utils { } def utilsInstance = new Utils() Utils.metaClass.version = "3.0" utilsInstance.metaClass.released = true assert utilsInstance.version == "3.0" assert utilsInstance.released == true Adding properties using MetaClass
  • 35. Adding properties using MetaClass class Utils { } def utilsInstance = new Utils() Utils.metaClass.version = "3.0" utilsInstance.metaClass.released = true assert utilsInstance.version == "3.0" assert utilsInstance.released == true
  • 36. class Utils { } def utilsInstance = new Utils() Utils.metaClass.version = "3.0" utilsInstance.metaClass.released = true assert utilsInstance.version == "3.0" assert utilsInstance.released == true Adding properties using MetaClass
  • 37. class Utils { } def utilsInstance = new Utils() Utils.metaClass.version = "3.0" utilsInstance.metaClass.released = true assert utilsInstance.version == "3.0" assert utilsInstance.released == true Adding properties using MetaClass
  • 38. // Integer assert '42' == 42.toString() Integer.metaClass.toString = { delegate == 42 ? 'The answer to life, the universe and everything' : String.valueOf(delegate) } assert 42.toString() == 'The answer to life, the universe and everything' assert 100.toString() == '100' // Boolean assert false.toBoolean() == false Boolean.metaClass.toBoolean = { !delegate } assert false.toBoolean() == true Overriding methods using MetaClass
  • 39. // Integer assert '42' == 42.toString() Integer.metaClass.toString = { delegate == 42 ? 'The answer to life, the universe and everything' : String.valueOf(delegate) } assert 42.toString() == 'The answer to life, the universe and everything' assert 100.toString() == '100' // Boolean assert false.toBoolean() == false Boolean.metaClass.toBoolean = { !delegate } assert false.toBoolean() == true Overriding methods using MetaClass
  • 40. // Integer assert '42' == 42.toString() Integer.metaClass.toString = { delegate == 42 ? 'The answer to life, the universe and everything' : String.valueOf(delegate) } assert 42.toString() == 'The answer to life, the universe and everything' assert 100.toString() == '100' // Boolean assert false.toBoolean() == false Boolean.metaClass.toBoolean = { !delegate } assert false.toBoolean() == true Overriding methods using MetaClass
  • 41. // Integer assert '42' == 42.toString() Integer.metaClass.toString = { delegate == 42 ? 'The answer to life, the universe and everything' : String.valueOf(delegate) } assert 42.toString() == 'The answer to life, the universe and everything' assert 100.toString() == '100' // Boolean assert false.toBoolean() == false Boolean.metaClass.toBoolean = { !delegate } assert false.toBoolean() == true Overriding methods using MetaClass
  • 42. // Integer assert '42' == 42.toString() Integer.metaClass.toString = { delegate == 42 ? 'The answer to life, the universe and everything' : String.valueOf(delegate) } assert 42.toString() == 'The answer to life, the universe and everything' assert 100.toString() == '100' // Boolean assert false.toBoolean() == false Boolean.metaClass.toBoolean = { !delegate } assert false.toBoolean() == true Overriding methods using MetaClass
  • 43. // Integer assert '42' == 42.toString() Integer.metaClass.toString = { delegate == 42 ? 'The answer to life, the universe and everything' : String.valueOf(delegate) } assert 42.toString() == 'The answer to life, the universe and everything' assert 100.toString() == '100' // Boolean assert false.toBoolean() == false Boolean.metaClass.toBoolean = { !delegate } assert false.toBoolean() == true Overriding methods using MetaClass
  • 44. Categories ▷ MetaClass changes are “persistent” ▷ Change metaclass in confined code ▷ MOP modified only in the closure
  • 45. Categories example class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } use (StringUtils) { println "Lorem ipsum".truncate(5) } try { println "Lorem ipsum".truncate(5) } catch (MissingMethodException mme) { println mme } // Execution Lorem groovy.lang.MissingMethodException: No signature of method: java.lang.String.truncate() is applicable for argument types: (java.lang.Integer) values: [5] Possible solutions: concat(java.lang.String), take(int)
  • 46. Categories example class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } use (StringUtils) { println "Lorem ipsum".truncate(5) } try { println "Lorem ipsum".truncate(5) } catch (MissingMethodException mme) { println mme } // Execution Lorem groovy.lang.MissingMethodException: No signature of method: java.lang.String.truncate() is applicable for argument types: (java.lang.Integer) values: [5] Possible solutions: concat(java.lang.String), take(int)
  • 47. Categories example class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } use (StringUtils) { println "Lorem ipsum".truncate(5) } try { println "Lorem ipsum".truncate(5) } catch (MissingMethodException mme) { println mme } // Execution Lorem groovy.lang.MissingMethodException: No signature of method: java.lang.String.truncate() is applicable for argument types: (java.lang.Integer) values: [5] Possible solutions: concat(java.lang.String), take(int)
  • 48. Categories example class StringUtils { static String truncate(String text, Integer length, Boolean overflow = false) { text.take(length) + (overflow ? '...' : '') } } use (StringUtils) { println "Lorem ipsum".truncate(5) } try { println "Lorem ipsum".truncate(5) } catch (MissingMethodException mme) { println mme } // Execution Lorem groovy.lang.MissingMethodException: No signature of method: java.lang.String.truncate() is applicable for argument types: (java.lang.Integer) values: [5] Possible solutions: concat(java.lang.String), take(int)
  • 49. class FileBinaryCategory { def static leftShift(File file, URL url) { def input def output try { input = url.openStream() output = new BufferedOutputStream(new FileOutputStream(file)) output << input } finally { input?.close() output?.close() } } } Categories example (II)
  • 50. class FileBinaryCategory { def static leftShift(File file, URL url) { def input def output try { input = url.openStream() output = new BufferedOutputStream(new FileOutputStream(file)) output << input } finally { input?.close() output?.close() } } } Categories example (II)
  • 51. class FileBinaryCategory { def static leftShift(File file, URL url) { def input def output try { input = url.openStream() output = new BufferedOutputStream(new FileOutputStream(file)) output << input } finally { input?.close() output?.close() } } } Categories example (II) File tmpFile = File.createTempFile('tmp_', '') use (FileBinaryCategory) { tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL() } println tmpFile // Execution /tmp/tmp_7428855173238452155
  • 52. class FileBinaryCategory { def static leftShift(File file, URL url) { def input def output try { input = url.openStream() output = new BufferedOutputStream(new FileOutputStream(file)) output << input } finally { input?.close() output?.close() } } } Categories example (II) File tmpFile = File.createTempFile('tmp_', '') use (FileBinaryCategory) { tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL() } println tmpFile // Execution /tmp/tmp_7428855173238452155
  • 53. class FileBinaryCategory { def static leftShift(File file, URL url) { def input def output try { input = url.openStream() output = new BufferedOutputStream(new FileOutputStream(file)) output << input } finally { input?.close() output?.close() } } } Categories example (II) File tmpFile = File.createTempFile('tmp_', '') use (FileBinaryCategory) { tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL() } println tmpFile // Execution /tmp/tmp_7428855173238452155
  • 54. class FileBinaryCategory { def static leftShift(File file, URL url) { def input def output try { input = url.openStream() output = new BufferedOutputStream(new FileOutputStream(file)) output << input } finally { input?.close() output?.close() } } } Categories example (II) File tmpFile = File.createTempFile('tmp_', '') use (FileBinaryCategory) { tmpFile << "http://groovy.codehaus.org/images/groovy-logo-medium.png".toURL() } println tmpFile // Execution /tmp/tmp_7428855173238452155
  • 55. Extension modules ▷ JAR file that provides extra methods ▷ Meta-information file ▷ Put jar in classpath to enhance classes
  • 56. // src/main/groovy/confess2015/StringUtilsExtension.groovy package confess2015 class StringUtilsExtension { static String truncate(String self, Integer length, Boolean overflow = false) { self.take(length) + (overflow ? '...' : '') } } package confess2015 import spock.lang.Specification class StringUtilsExtensionSpec extends Specification { void 'test trucate'() { expect: "Lorem" == "Lorem ipsum".truncate(5) "Lorem..." == "Lorem ipsum".truncate(5, true) } } // Execute with: // gradle build // groovy -cp build/libs/string- extensions-1.0.jar ExtensionExample1.groovy assert "Lorem..." == "Lorem ipsum". truncate(5, true) # src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule moduleName = string-utils-module moduleVersion = 0.1 extensionClasses = confess2015.StringUtilsExtension Extension modules example
  • 57. Extension modules example // src/main/groovy/confess2015/StringUtilsExtension.groovy package confess2015 class StringUtilsExtension { static String truncate(String self, Integer length, Boolean overflow = false) { self.take(length) + (overflow ? '...' : '') } } # src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule moduleName = string-utils-module moduleVersion = 0.1 extensionClasses = confess2015.StringUtilsExtension package confess2015 import spock.lang.Specification class StringUtilsExtensionSpec extends Specification { void 'test trucate'() { expect: "Lorem" == "Lorem ipsum".truncate(5) "Lorem..." == "Lorem ipsum".truncate(5, true) } } // Execute with: // gradle build // groovy -cp build/libs/string- extensions-1.0.jar ExtensionExample1.groovy assert "Lorem..." == "Lorem ipsum". truncate(5, true)
  • 58. Extension modules example // src/main/groovy/confess2015/StringUtilsExtension.groovy package confess2015 class StringUtilsExtension { static String truncate(String self, Integer length, Boolean overflow = false) { self.take(length) + (overflow ? '...' : '') } } package confess2015 import spock.lang.Specification class StringUtilsExtensionSpec extends Specification { void 'test trucate'() { expect: "Lorem" == "Lorem ipsum".truncate(5) "Lorem..." == "Lorem ipsum".truncate(5, true) } } // Execute with: // gradle build // groovy -cp build/libs/string- extensions-1.0.jar ExtensionExample1.groovy assert "Lorem..." == "Lorem ipsum". truncate(5, true) # src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule moduleName = string-utils-module moduleVersion = 0.1 extensionClasses = confess2015.StringUtilsExtension
  • 59. Extension modules example // src/main/groovy/confess2015/StringUtilsExtension.groovy package confess2015 class StringUtilsExtension { static String truncate(String self, Integer length, Boolean overflow = false) { self.take(length) + (overflow ? '...' : '') } } package confess2015 import spock.lang.Specification class StringUtilsExtensionSpec extends Specification { void 'test trucate'() { expect: "Lorem" == "Lorem ipsum".truncate(5) "Lorem..." == "Lorem ipsum".truncate(5, true) } } // Execute with: // gradle build // groovy -cp build/libs/string- extensions-1.0.jar ExtensionExample1.groovy assert "Lorem..." == "Lorem ipsum". truncate(5, true) # src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule moduleName = string-utils-module moduleVersion = 0.1 extensionClasses = confess2015.StringUtilsExtension
  • 60. // src/main/groovy/confess2015/StringUtilsExtension.groovy package confess2015 class StringUtilsExtension { static String truncate(String self, Integer length, Boolean overflow = false) { self.take(length) + (overflow ? '...' : '') } } package confess2015 import spock.lang.Specification class StringUtilsExtensionSpec extends Specification { void 'test trucate'() { expect: "Lorem" == "Lorem ipsum".truncate(5) "Lorem..." == "Lorem ipsum".truncate(5, true) } } // Execute with: // gradle build // groovy -cp build/libs/string- extensions-1.0.jar ExtensionExample1.groovy assert "Lorem..." == "Lorem ipsum". truncate(5, true) Extension modules example # src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule moduleName = string-utils-module moduleVersion = 0.1 extensionClasses = confess2015.StringUtilsExtension
  • 61. Mixins ▷ “Bring in” or “mix in” implementations from multiple classes ▷ Calls first routed to mixed-in class ▷ Last mixin wins ▷ Not easily un-done
  • 62. class SpidermanPower { String spiderSense() { "Using spider-sense..." } } Mixins example @Mixin([SpidermanPower]) class Person {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert !(person instanceof SpidermanPower) Person.mixin SupermanPower assert person.fly() == "Flying..." assert !(person instanceof SupermanPower) class SupermanPower { String fly() { "Flying..." } }
  • 63. @Mixin([SpidermanPower]) class Person {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert !(person instanceof SpidermanPower) Person.mixin SupermanPower assert person.fly() == "Flying..." assert !(person instanceof SupermanPower) class SupermanPower { String fly() { "Flying..." } } class SpidermanPower { String spiderSense() { "Using spider-sense..." } } Mixins example
  • 64. @Mixin([SpidermanPower]) class Person {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert !(person instanceof SpidermanPower) Person.mixin SupermanPower assert person.fly() == "Flying..." assert !(person instanceof SupermanPower) class SupermanPower { String fly() { "Flying..." } } class SpidermanPower { String spiderSense() { "Using spider-sense..." } } Mixins example
  • 65. @Mixin([SpidermanPower]) class Person {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert !(person instanceof SpidermanPower) Person.mixin SupermanPower assert person.fly() == "Flying..." assert !(person instanceof SupermanPower) class SupermanPower { String fly() { "Flying..." } } class SpidermanPower { String spiderSense() { "Using spider-sense..." } } Mixins example
  • 66. @Mixin([SpidermanPower]) class Person {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert !(person instanceof SpidermanPower) Person.mixin SupermanPower assert person.fly() == "Flying..." assert !(person instanceof SupermanPower) class SpidermanPower { String spiderSense() { "Using spider-sense..." } } Mixins example class SupermanPower { String fly() { "Flying..." } }
  • 67. @Mixin([SpidermanPower]) class Person {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert !(person instanceof SpidermanPower) Person.mixin SupermanPower assert person.fly() == "Flying..." assert !(person instanceof SupermanPower) class SpidermanPower { String spiderSense() { "Using spider-sense..." } } Mixins example class SupermanPower { String fly() { "Flying..." } }
  • 68. Traits ▷ Groovy 2.3+ ▷ Similar to Java 8 default methods ▷ Supported in JDK 6, 7 and 8 ▷ Stateful ▷ Composition over inheritance ▷ Documentation
  • 69. class Person implements SpidermanPower {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert person instanceof SpidermanPower def person2 = person.withTraits SupermanPower assert person2.fly() == "Flying..." assert person2 instanceof SupermanPower Traits example trait SpidermanPower { String spiderSense() { "Using spider-sense..." } } trait SupermanPower { String fly() { "Flying..." } }
  • 70. class Person implements SpidermanPower {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert person instanceof SpidermanPower def person2 = person.withTraits SupermanPower assert person2.fly() == "Flying..." assert person2 instanceof SupermanPower Traits example trait SpidermanPower { String spiderSense() { "Using spider-sense..." } } trait SupermanPower { String fly() { "Flying..." } }
  • 71. class Person implements SpidermanPower {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert person instanceof SpidermanPower def person2 = person.withTraits SupermanPower assert person2.fly() == "Flying..." assert person2 instanceof SupermanPower Traits example trait SpidermanPower { String spiderSense() { "Using spider-sense..." } } trait SupermanPower { String fly() { "Flying..." } }
  • 72. class Person implements SpidermanPower {} def person = new Person() assert person.spiderSense() == "Using spider-sense..." assert person instanceof SpidermanPower def person2 = person.withTraits SupermanPower assert person2.fly() == "Flying..." assert person2 instanceof SupermanPower Traits example trait SpidermanPower { String spiderSense() { "Using spider-sense..." } } trait SupermanPower { String fly() { "Flying..." } }
  • 74. MOP Method Synthesis ▷ Dynamically figure out behaviour upon invocation ▷ It may not exist until it's called/executed ▷ “Intercept, Cache, Invoke” pattern
  • 75. def p = new Person(name: 'Iván', age: 34) assert p.respondsTo('sayHi') assert p.respondsTo('sayHiTo', String) assert !p.respondsTo('goodbye') assert p.hasProperty('name') assert !p.hasProperty('country') Check for methods and properties class Person { String name Integer age String sayHi() { "Hi, my name is ${name} and I'm ${age}" } String sayHiTo(String name) { "Hi ${name}, how are you?" } }
  • 76. def p = new Person(name: 'Iván', age: 35) assert p.respondsTo('sayHi') assert p.respondsTo('sayHiTo', String) assert !p.respondsTo('goodbye') assert p.hasProperty('age') assert !p.hasProperty('country') Check for methods and properties class Person { String name Integer age String sayHi() { "Hi, my name is ${name} and I'm ${age}" } String sayHiTo(String name) { "Hi ${name}, how are you?" } }
  • 77. Check for methods and properties class Person { String name Integer age String sayHi() { "Hi, my name is ${name} and I'm ${age}" } String sayHiTo(String name) { "Hi ${name}, how are you?" } } def p = new Person(name: 'Iván', age: 35) assert p.respondsTo('sayHi') assert p.respondsTo('sayHiTo', String) assert !p.respondsTo('goodbye') assert p.hasProperty('age') assert !p.hasProperty('country')
  • 78. Check for methods and properties class Person { String name Integer age String sayHi() { "Hi, my name is ${name} and I'm ${age}" } String sayHiTo(String name) { "Hi ${name}, how are you?" } } def p = new Person(name: 'Iván', age: 35) assert p.respondsTo('sayHi') assert p.respondsTo('sayHiTo', String) assert !p.respondsTo('goodbye') assert p.hasProperty('age') assert !p.hasProperty('country')
  • 79. MethodMissing example ▷ Requirements: – Send notifications to users by different channels – +50 notifications – Not all notifications by all channels – Extensible and open to future modifications
  • 80. MethodMissing example abstract class Channel { void sendNewFollower(String username, String follower) { } void sendNewMessage(String username, String msg) { } ... } class EmailChannel extends Channel { void sendNewFollower(String username, String follower) { println "Sending email notification to '${username}' for new follower '${follower}'" } void sendNewMessage(String username, String msg) { println "Sending email notification to '${username}' for new message '${msg}'" } } class MobilePushChannel extends Channel { void sendNewFollower(String username, String follower) { println "Sending mobile push notification to '${username}' for new follower '${follower}'" } }
  • 81. MethodMissing example abstract class Channel { void sendNewFollower(String username, String follower) { } void sendNewMessage(String username, String msg) { } ... } class EmailChannel extends Channel { void sendNewFollower(String username, String follower) { println "Sending email notification to '${username}' for new follower '${follower}'" } void sendNewMessage(String username, String msg) { println "Sending email notification to '${username}' for new message '${msg}'" } } class MobilePushChannel extends Channel { void sendNewFollower(String username, String follower) { println "Sending mobile push notification to '${username}' for new follower '${follower}'" } }
  • 82. MethodMissing example abstract class Channel { void sendNewFollower(String username, String follower) { } void sendNewMessage(String username, String msg) { } ... } class EmailChannel extends Channel { void sendNewFollower(String username, String follower) { println "Sending email notification to '${username}' for new follower '${follower}'" } void sendNewMessage(String username, String msg) { println "Sending email notification to '${username}' for new message '${msg}'" } } class MobilePushChannel extends Channel { void sendNewFollower(String username, String follower) { println "Sending mobile push notification to '${username}' for new follower '${follower}'" } }
  • 83. MethodMissing example class NotificationService { List channels = [] def methodMissing(String name, args) { System.out.println "...methodMissing called for ${name} with args ${args}" // Generate the implementation def implementation = { Object[] methodArgs -> channels.each { channel -> def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs) return metaMethod.invoke(channel, methodArgs) } } // Cache the implementation in the metaClass NotificationService instance = this instance.metaClass."$name" = implementation // Execute it! implementation(args) } }
  • 84. MethodMissing example class NotificationService { List channels = [] def methodMissing(String name, args) { System.out.println "...methodMissing called for ${name} with args ${args}" // Generate the implementation def implementation = { Object[] methodArgs -> channels.each { channel -> def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs) return metaMethod.invoke(channel, methodArgs) } } // Cache the implementation in the metaClass NotificationService instance = this instance.metaClass."$name" = implementation // Execute it! implementation(args) } }
  • 85. MethodMissing example class NotificationService { List channels = [] def methodMissing(String name, args) { System.out.println "...methodMissing called for ${name} with args ${args}" // Generate the implementation def implementation = { Object[] methodArgs -> channels.each { channel -> def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs) return metaMethod.invoke(channel, methodArgs) } } // Cache the implementation in the metaClass NotificationService instance = this instance.metaClass."$name" = implementation // Execute it! implementation(args) } } notificationService.sendNewFollower(...) notificationService.sendNewMessage(...)
  • 86. MethodMissing example class NotificationService { List channels = [] def methodMissing(String name, args) { System.out.println "...methodMissing called for ${name} with args ${args}" // Generate the implementation def implementation = { Object[] methodArgs -> channels.each { channel -> def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs) return metaMethod.invoke(channel, methodArgs) } } // Cache the implementation in the metaClass NotificationService instance = this instance.metaClass."$name" = implementation // Execute it! implementation(args) } }
  • 87. MethodMissing example class NotificationService { List channels = [] def methodMissing(String name, args) { System.out.println "...methodMissing called for ${name} with args ${args}" // Generate the implementation def implementation = { Object[] methodArgs -> channels.each { channel -> def metaMethod = channel.metaClass.getMetaMethod(name, methodArgs) return metaMethod.invoke(channel, methodArgs) } } // Cache the implementation in the metaClass NotificationService instance = this instance.metaClass."$name" = implementation // Execute it! implementation(args) } }
  • 88. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")
  • 89. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")
  • 90. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")
  • 91. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")
  • 92. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")class EmailChannel extends Channel { void sendNewFollower(String username, String follower) {…} void sendNewMessage(String username, String msg) {…} } class MobilePushChannel extends Channel { void sendNewFollower(String username, String follower) {…} }
  • 93. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")
  • 94. MethodMissing example // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!' def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!")
  • 95. MethodMissing example def notificationService = new NotificationService( channels: [new EmailChannel(), new MobilePushChannel()] ) assert !notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("John", "Peter") assert notificationService.respondsTo('sendNewFollower', String, String) notificationService.sendNewFollower("Mary", "Steve") notificationService.sendNewMessage("Iván", "Hello!") // Execution ...methodMissing called for sendNewFollower with args [John, Peter] Sending email notification to 'John' for new follower 'Peter' Sending mobile push notification to 'John' for new follower 'Peter' Sending email notification to 'Mary' for new follower 'Steve' Sending mobile push notification to 'Mary' for new follower 'Steve' ...methodMissing called for sendNewMessage with args [Iván, Hello!] Sending email notification to 'Iván' for new message 'Hello!'
  • 97. Compile-time metaprogramming ▷ Advance feature ▷ Analyze/modify program structure at compile time ▷ Cross-cutting features ▷ Write code that generates bytecode
  • 98. AST and compilation ▷ AST: Abstract Syntax Tree ▷ AST modified during compilation ▷ Hook into the phases ▷ Initialization, Parsing, Conversion, Semantic analysis, Canonicalization, Instruction selection, Class generation, Output, Finalization
  • 100. Global AST Transformations ▷ No annotation ▷ Meta-information file ▷ Applied to all code during compilation ▷ Any compilation phase ▷ Grails uses intensively in GORM
  • 102. Local AST Transformations ▷ Annotate code ▷ No meta-information file ▷ Easy to debug
  • 103. Steps to create local AST Interface AST Enjoy!
  • 104. Local AST example package confess2015 import ... @Retention(RetentionPolicy.SOURCE) @Target([ElementType.TYPE]) @GroovyASTTransformationClass("confess2015.VersionASTTransformation") @interface Version { String value() } class VersionedClass { public static final String VERSION = "1.0" } import confess2015.Version @Version('1.0') class VersionedClass { }
  • 105. Local AST example class VersionedClass { public static final String VERSION = "1.0" } package confess2015 import ... @Retention(RetentionPolicy.SOURCE) @Target([ElementType.TYPE]) @GroovyASTTransformationClass("confess2015.VersionASTTransformation") @interface Version { String value() } import confess2015.Version @Version('1.0') class VersionedClass { }
  • 106. Local AST example class VersionedClass { public static final String VERSION = "1.0" } package confess2015 import ... @Retention(RetentionPolicy.SOURCE) @Target([ElementType.TYPE]) @GroovyASTTransformationClass("confess2015.VersionASTTransformation") @interface Version { String value() } import confess2015.Version @Version('1.0') class VersionedClass { }
  • 107. Local AST example @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) class VersionASTTransformation extends AbstractASTTransformation { @Override public void visit(final ASTNode[] nodes, final SourceUnit source) { if (nodes.length != 2) { return } if (nodes[0] instanceof AnnotationNode && nodes[1] instanceof ClassNode) { def annotation = nodes[0] def version = annotation.getMember('value') if (version instanceof ConstantExpression) { nodes[1].addField('VERSION', ACC_PUBLIC | ACC_STATIC | ACC_FINAL, ClassHelper.STRING_TYPE, version) } else { source.addError(new SyntaxException("Invalid value for annotation", annotation.lineNumber, annotation.columnNumber)) } } } }
  • 108. Local AST example @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) class VersionASTTransformation extends AbstractASTTransformation { @Override public void visit(final ASTNode[] nodes, final SourceUnit source) { if (nodes.length != 2) { return } if (nodes[0] instanceof AnnotationNode && nodes[1] instanceof ClassNode) { def annotation = nodes[0] def version = annotation.getMember('value') if (version instanceof ConstantExpression) { nodes[1].addField('VERSION', ACC_PUBLIC | ACC_STATIC | ACC_FINAL, ClassHelper.STRING_TYPE, version) } else { source.addError(new SyntaxException("Invalid value for annotation", annotation.lineNumber, annotation.columnNumber)) } } } }
  • 109. Local AST example // Execute with: // gradle build // groovy -cp build/libs/add-version-1.0.jar LocalASTExample.groovy import confess.Version @Version('1.0') class VersionedClass { } println VersionedClass.VERSION // Execution 1.0
  • 110. Local AST example // Execute with: // gradle build // groovy -cp build/libs/add-version-1.0.jar LocalASTExample.groovy import confess.Version @Version('1.0') class VersionedClass { } println VersionedClass.VERSION // Execution 1.0
  • 111. Local AST example // Execute with: // gradle build // groovy -cp build/libs/add-version-1.0.jar LocalASTExample.groovy import confess.Version @Version('1.0') class VersionedClass { } println VersionedClass.VERSION // Execution 1.0
  • 112. 3. Why we should use metaprogramming?
  • 113. Let’s review some concepts Metaprogramming out-of-the box Easy and very powerful Write better code Add behaviour easily Take advantage of this power Because Groovy, it's groovy
  • 114. With great power comes great responsibility