Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize self-defined objects in Groovy

Tags:

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?

like image 369
Vorg van Geir Avatar asked Oct 11 '22 04:10

Vorg van Geir


1 Answers

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

like image 110
Angel O'Sphere Avatar answered Dec 04 '22 23:12

Angel O'Sphere