Here is a small sample code I wrote that shows object serialization in groovy. when I ran this directly in groovy shell it did not work off the bat. I had to move the class Name to separate file Name.groovy and make sure it is in the class-path to work. Here is the link to original discussion on groovy forum.

// put this in a file named Name.groovy and compile using groovyc 
class Name implements Serializable  {
   def fname, lname
}
// Now run the code below to see the Object serialization and de-serialization.
def test1= new Name(fname: "fn1", lname : "ln1")
def test2 = new Name(fname: "fn2", lname: "ln2")
//serialization
new File("C:/config.txt").withObjectOutputStream { out ->
    out << test1
    out << test2
}
//de-serialization
new File("C:/config.txt").withObjectInputStream { instream ->
    instream.eachObject { 
        println it
    }
}

4 Comments

  1. Edgar says:

    This didn’t work for me. I see the Groovy API is now extended with an extra ClassLoader parameter for withObjectInputStream, but it’s not implemented in the version I’m using (WebSphere sMash). As the sollution on the groovy JIRA says ( http://jira.codehaus.org/browse/GROOVY-1627 ), I ended up extending ObjectInputStream (as Java class), for overriding resolveClass:

    [code]public class GroovyObjectInputStream extends ObjectInputStream {

    private ClassLoader myClassLoader;

    public GroovyObjectInputStream(ClassLoader myClassLoader) throws IOException, SecurityException {
    super();
    this.myClassLoader = myClassLoader;
    }

    public GroovyObjectInputStream(InputStream in, ClassLoader myClassLoader) throws IOException {
    super(in);
    this.myClassLoader = myClassLoader;
    }

    @Override
    protected Class resolveClass(ObjectStreamClass desc) throws IOException,
    ClassNotFoundException {
    String name = desc.getName();
    return Class.forName(name, false, myClassLoader);
    }
    }
    [/code]

    Then use that ObjectInputStream:

    [code]def file = new my.utils.GroovyObjectInputStream ( new FileInputStream ( “/home/edgar/objectinput” ), getClass().classLoader )
    def input = file.readObject()
    [/code]

  2. Edgar says:

    Oh, just to clarify why it didn’t work. ObjectInputStream uses the last used ClassLoader in the JVM. In my situation, this appearantly is NOT the same loader as Groovy uses to load my groovybean.
    One other thing: keep in mind that the serialVersionUID changes every time you compile, even if the bean did not change! I’m using this for temporary caching database output for development purpose (offload the database server). Might be better not to do that and use a Java bean instead to prevent the serialVersionUID from changing every time.

Leave a Reply