Watch This Video
---------------------------------------------------------------------------------------------------[Exercise] Runtime Metaprogramming
GroovyObject
Create a class and implement each of the following methods from the GroovyObject Interface
invokeMethod
getProperty
setProperty
Expando
Create an Expando Class
Add some properties and methods to it
Knowing that a class's metaclass is an expando to create your own class and add properties and methods to it.
Times Two
Add a new method to the Integer class called `timesTwo`
This method should be available to any instance of Integer
What is another approach that we can take to create this method that would be a little more controlled?
//Code
//Developer.groovy
class Developer{
String first
String last
String email
List languages
Developer(){
}
def invokeMethod(String name,Object args){
println "invokeMethod()called with args $args"
}
defgetProperty(String property){
println"getProperty called..."
metaClass.getProperty(this,property)
}
void setProperty(String property,Object newValue){
println"setProperty() called with name $property and newValue $newValue"
metaClass.setProperty(this,property,newValue)
}
}
//GroovyObjectDemo.groovy
Developer developer = newDeveloper(first:"Dan",last:"Vega",email:"danvega@gmail.com")
developer.writeCode("Groovy")
println developer.first
developer.languages=["Groovy","Java]
//ExpandoDemo.groovy
Expando e = new Expando()
e.first="Dan"
e.last="Vega"
e.email="danvega@gmail.com"
e.getFullName={
"$first,$last"
}
println e.toString()
println e.getFullName()
@groovy.transform.ToString(includeNames =true)
class Person {
String first,last
}
Person p=new Person(first:"Dan,last:"Vega")
p.metaClass.email="danvega@gmail.com"
println p
println p.email
//SquaredDemo.groovy
Integer.metaClass.timesTwo={delegate *2}
println 2.timesTwo()
println 4.timesTwo()
println 5.timesTwo()
println 6.timesTwo()
No comments:
Post a Comment
Note: only a member of this blog may post a comment.