How to cast an object in class loaded in classloader

552 views Asked by At

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!!!

1

There are 1 answers

0
papacito On BEST ANSWER

I managed to solve your problem. Let me show you a working example

Some Employee class, that I use

public class Employee implements java.io.Serializable
{
    public String name;
    public String address;
}

Then the Main class

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