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{} 

... causes an error ...

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

... when trying to reload an object in the second try block. It works fine when the class is a predefined class like java.util.List. The code above also works fine when converting a string for a string in Java .

How can I make it work in Groovy?

+4
source share
1 answer

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

+4
source

Source: https://habr.com/ru/post/1368937/


All Articles