DataBeans in Groovy

Okay, not many will be interested in this perhaps, but I thought I might put it up. I use a data objects framework called DataBeans which you can find as part of the sticker.jar file in the Sticker instant messaging tool (http://tickertape.org/projects/sticker). DataBeans gives you a JavaBeans style interface to nested hashmaps, but it has an event mechanism, so you can listen at the root bean and hear changes inside (including path info to the change). Neat huh.

Anyway, my supervisor said he’d be impressed if I could do some Groovy (http://groovy.codehaus.org) meta-programming to allow access to DataBean properties without having to use the typical getValue(String name) and setValue(String name, Object value).

After a little looking around I wrote this program which adds a couple of methods to the DataBean’s meta-class (what supports most of Groovy’s dynamic behaviour). All you need is sticker.jar on the classpath and this will work without issue (oh, I’m using groovy 1.6.0 but I think it’s available in 1.5.x).

import dsto.dfc.databeans.DataBean

DataBean jdb = new DataBean()
jdb.setValue("a", 1)
jdb.setValue("b", true)

DataBean jdb2 = new DataBean()
jdb2.setValue("aa", 42.0)

jdb.setValue("c", jdb2)

println jdb

DataBean.metaClass.propertyMissing = { String name ->
  value = delegate.getValue(name)
// the commented code will allow statements like db.a.b = 'c' when a is undefined
//  if (!value) {
//    value = new DataBean()
//    delegate.setValue(name, value)
//  }
  return value
}
DataBean.metaClass.propertyMissing = { String name, value ->
  delegate.setValue(name, value)
}

println jdb.c.aa
jdb.c.bb = 'hello'
println jdb.c

try {
  println jdb.d.dd = 3
} catch (NullPointerException ex) {
  println "NPE on 'jdb.d.dd = 3': ${ex.getMessage()}"
}
println jdb

Even if it’s of no use to you, hopefully it may intrigue you to look at Groovy or DataBeans (when there’s a link for that I’ll post it).

  • Share/Bookmark

Comments are closed.


Theme Tweaker by Unreal