Oct 222010

While playing with Groovy and Db4o I ran across a few errors that nearly put me right off Db4o. But after half a day tinkering I have found that it’s not really a problem with Db4o. If you are getting any of the following errors when trying to use Db4o and Groovy then perhaps this post can help.


cannot be cast to com.db4o.reflect.generic.GenericObject // or person.getClass() is this.
// When trying to access a method or property of a retrieved object.
(G) Person // GenericObject, e.g: println person

The problem arises when the script tries to open an existing database with objects in it and is something to do with reflection and class loading that Db4o does. Now Db4o is a Java OODBMS and all the examples are in Java, hence compiled before run! None of the suggested solutions that I found around the `net such as using file.canonicalPath or using a new config or packages or using a newer jar (db4o- made the slightest difference.

The solution: `groovyc Person.groovy`

That’s correct we need a compiled Java class file so that Db4o can load/reflect or whatever and cast the returned data back to Person instead of creating a GenericObject! Every time Person.groovy changes we need to compile it again otherwise the source file will be used.


class Person {
    String name
    String toString() {
        "My name is $name"

Groovy script, PersonExample.groovy:

#!/usr/bin/env groovy
import com.db4o.*
def db
def file = new File("db.db4o")
def jack = new Person(name:"Jack")
def jill = new Person(name:"Jill")
try {
    db = Db4oEmbedded.openFile(file.absolutePath)
finally {
db = null // Just to be clear.
try {
    db = Db4oEmbedded.openFile(file.absolutePath)
    def persons = db.query(Person)
    for(person in persons) {
        println person
finally {

– download and place db4o- in $GROOVY_HOME/lib.
– groovyc Person.groovy
– chmod +x PersonExample.groovy (make the script executable)
– ./PersonExample.groovy or `groovy PersonExample.groovy`

Gavin Kromhout:

Thank you for visiting.
Do look around.
Do leave a comment.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>