Java Mailing List Archive

http://www.gg3721.com/

Home » user.groovy »

[groovy-user] MetaClass Question

James Hughes

2008-08-19

Replies: Find Java Web Hosting

Author LoginPost Reply
I found an interesting issue when playing with metaclasses Apoliges for the large amount of

What I am trying to do in my code is this

Create an ArrayList of Person objects (call it people) then to demostrate the power of metaprogramming extend the people list wiih a few closures/methods that filter the list. My code looks like this

class Person {
  def name,age,sex,employed
}
def people = [
  new Person(name:"Person 1", age:67, sex:'male', employed:true),
  new Person(name:"Person 4", age:42, sex:'male', employed:true),
  new Person(name:"Person 8", age:21, sex:'male', employed:false)
]
/* sorting by age */
def byAge = {a,b ->
  a.age <=> b.age
}
/* ADD FILTERS DIRECTLY TO LIST */
people.class.metaClass.olderThanEighteen = {
  delegate.findAll{it.age > 18}
}
people.metaClass.males = {
  delegate.findAll{it.sex.equals('male')}
}
people.metaClass.inEmployment = {
  delegate.findAll{it.employed}
}
// more expressive??!
def filtered = people.males().olderThanEighteen().inEmployment().sort(byAge)
filtered.each {
  println "$it.name is an employed male older than 18"
}

When I run this code I get this error

groovy.lang.MissingPropertyException: No such property: olderThanEighteen for class: groovy.lang.MetaClassImpl
at Script0.run(Script0:14)

The quirk comes when I modify the "people.metaClass.olderThenEighteen" line to be "people.class.metaClass.olderThenEighteen" everything works from then onwards. Even the unmodifed lines "people.metaClass.males" and "people.metaClass.inEmployment". Can anyone explain why this is the case?

James.


--------------------------------------------------------------------
This e-mail is intended solely for the addressee and is strictly confidential; if you are not the addressee please destroy the message and all copies. Any opinion or information contained in this email or its attachments that does not relate to the business of Kainos
is personal to the sender and is not given by or endorsed by Kainos. Kainos is the trading name of Kainos Software Limited, registered in Northern Ireland under company number: NI19370, having its registered offices at: Kainos House, 4-6 Upper Crescent, Belfast, BT7 1NT,
Northern Ireland. Registered in the UK for VAT under number: 454598802 and registered in Ireland for VAT under number: 9950340E. This email has been scanned for all known viruses by MessageLabs but is not guaranteed to be virus free; further terms and conditions may be
found on our website - www.kainos.com


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

  http://xircles.codehaus.org/manage_email


©2008 gg3721.com - Jax Systems, LLC, U.S.A.