我设法解决了你的问题。让我向您展示一个工作示例
Employee
我使用的一些课程
public class Employee implements java.io.Serializable
{
public String name;
public String address;
}
然后Main
上课
class Main {
public static void main(String[] args) {
Employee e1 = new Employee()
e1.name = 'John'
e1.address = 'Main Street'
byte[] bytes = []
ByteArrayOutputStream stream = new ByteArrayOutputStream()
ObjectOutputStream out = new ObjectOutputStream(stream)
out.writeObject(e1)
bytes = stream.toByteArray()
out.close()
stream.close()
Object o = null
new ByteArrayInputStream(bytes).withObjectInputStream(Main.getClassLoader()){ gin ->
o = gin.readObject()
}
print o instanceof Employee
println 'Deserialized Employee...'
println 'Name: ' + o.name
println 'Address: ' + o.address
}
}
Instead of doing getClass().classLoader
, which was throwing a java.lang.ClassNotFoundException
, I am doing Main.getClassLoader()
. This classloader is able to find my Employee
class.
Moreover, you don't really need to cast the object, it is groovy, its dynamic, so you get the name
and address
fields at runtime.
But, you can always check the type of the object and then cast it:
print o instanceof Employee
this will return true