Vorg van Geir
Vorg van Geir

Reputation: 682

How to serialize self-defined objects in Groovy

This code...

class A implements Serializable{
  String str
  int n
}

try{
  def a= new A(str:'abc', n:7)
  def out= new ObjectOutputStream(new FileOutputStream('serializedObject.obj'))
  out.writeObject(a)
  out.close()
}finally{}

try{
  def inp= new ObjectInputStream(new FileInputStream('serializedObject.obj'))
  def a2= inp.readObject()
  inp.close()
}finally{}

...produces error...

java.lang.ClassNotFoundException: A
    at java_io_ObjectInput$readObject.call(Unknown Source)
    at otherRun.run(otherRun.groovy:16)

...when attempting to reload the object in the 2nd try block. It works OK when the class is a predefined class such as java.util.List. The above code also works OK when converted line-for-line into Java.

How can I get it working in Groovy?

Upvotes: 5

Views: 6552

Answers (1)

Angel O'Sphere
Angel O'Sphere

Reputation: 2666

Put your "class A" into its own file and make sure the "A.class" file is availbale (in classpath) where you read the object.

Upvotes: 4

Related Questions