I am new to Stack Overflow. I have created a Groovy class loader's object in which I have loaded all the classes required by my script. I have task of serializing and deserializing an object created of one of the class that is loaded in class loader. Problem is while deserializing I am not able to cast the object in the class as class in loaded in class loader. I don't know how to cast an object in a class that is loaded in a class loader. Can some one help me in this. The ????? in below snippet is a class that is loaded in class loader but how shall I achieve this.
Object o = null
new ByteArrayInputStream(bytes).withObjectInputStream(getClass().classLoader){ gin ->
o = (?????)gin.readObject() }
Thanks in advance!!!
I managed to solve your problem. Let me show you a working example
Some
Employee
class, that I useThen the
Main
classInstead of doing
getClass().classLoader
, which was throwing ajava.lang.ClassNotFoundException
, I am doingMain.getClassLoader()
. This classloader is able to find myEmployee
class.Moreover, you don't really need to cast the object, it is groovy, its dynamic, so you get the
name
andaddress
fields at runtime.But, you can always check the type of the object and then cast it:
this will return
true