ClassNotFoundException when deserializing a binary class file's contents

前端 未结 7 1745
[愿得一人]
[愿得一人] 2021-01-12 16:32

I don\'t know much about Java. I\'m trying to read a file containing an int and various instances of a class called \"Automobile\". When I deserialize it, though, the progra

7条回答
  •  温柔的废话
    2021-01-12 16:48

    Ive had a similar problem with a ObjectInputStream reading serialized Objects. The classes for those Objects i added at runtime with a URLClassloader. The problem was that the ObjectInputStream did not use the Thread ClassLoader which i set with

    Thread.currentThread().setContextClassLoader(cl);
    

    but instead the AppClassLoader, which you cannot customize with java 9. So i made my own ObjectInputStream as a subtype of the original one and overidden the resolveClass Method:

    @Override
    protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
        String name = desc.getName();
        try {
            return Class.forName(name, false, Thread.currentThread()
                    .getContextClassLoader());
        } catch (ClassNotFoundException ex) {
            Class cl = primClasses.get(name);
            if (cl != null) {
                return cl;
            } else {
                throw ex;
            }
        }
    }
    

提交回复
热议问题