JoachimR
JoachimR

Reputation: 5258

How to convert byte[] to Object and vice versa in Groovy

I am trying to convert a byte[] to an Object using Groovy. My actual Groovy Class that is represented by the byte array implements the Serializable interface and is stored in a separate Groovy class file. However I always get a ClassNotFoundException of this class when trying to call my toObject function. My code is written in Java and works when using Java but not when using Groovy.

private static byte[] toByteArray(Object obj) {
    byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        bos.close();
        bytes = bos.toByteArray();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return bytes;
}


private static Object toObject(byte[] bytes) {
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        obj = ois.readObject();
    } catch (Exception ex) {
        ex.printStackTrace(); // ClassNotFoundException
    }
    return obj;
}

What is the best way to do this?

Edit: A class that would be used in this context where the ClassNotFoundException would occur is something like this:

public class MyItem implements Serializable {

/**
 *
 */
private static final long serialVersionUID = -615551050422222952L;

public String text


MyItem() {
    this.text = ""
}
}

Then testing the whole thing:

    void test() {
        MyItem item1 = new MyItem ()
        item1.text = "bla"

        byte[] bytes = toByteArray(item1) // works

        Object o = toObject(bytes) // ClassNotFoundException: MyItem

        MyItem item2 = (MyItem) o

        System.out.print(item.text + " <--> " + item2.text)
    }

Upvotes: 0

Views: 3382

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

My guess (and this is what @JustinPiper suggested as well) is that you are not compiling your groovy class before referencing it. You must compile your groovy class using groovyc and make sure that the compiled class file is placed on the classpath (probably in the same file as the java test class).

Upvotes: 1

Related Questions