0

我是堆栈溢出的新手。我创建了一个 Groovy 类加载器对象,在其中加载了脚本所需的所有类。我的任务是序列化和反序列化由类加载器中加载的类之一创建的对象。问题是在反序列化时我无法将类中的对象转换为类加载器中加载的类。我不知道如何在类加载器中加载的类中转换对象。有人可以帮助我吗?这 ?????在下面的代码片段中是一个在类加载器中加载的类,但我应该如何实现这一点。

Object o = null
new ByteArrayInputStream(bytes).withObjectInputStream(getClass().classLoader){ gin ->
                                o = (?????)gin.readObject() }

提前致谢!!!

4

1 回答 1

0

我设法解决了你的问题。让我向您展示一个工作示例

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

于 2014-08-09T14:46:03.800 回答