简体   繁体   中英

Unable to load class exception during Kryo deserialization

I am using Kryo for serialization / deserialization and not registering classes beforehand (I am working on that). That said, upon deserialization, I am getting the exception:

Unable to load class shell.api.model.BatteryStatuo with kryo's ClassLoader. Retrying with current..

Now, my classname is actually shell.api.model.BatteryStatus so I'm not sure what happened during serialization.

Is there a limitation on the length of the classname?

Also, as I am serializing JPA entities which have nested structures and likely have circular references, will that pose a potential issue? I would think I'd see a stack overflow exception if so.

This is a snippet of serializing an object:

protected final Kryo kryo = new Kryo();


try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    try (final Output output = new Output(baos)) {
          kryo.writeObject(output, data);
        }
      return (baos.toByteArray());
    } catch (IOException e) {
      LOGGER.error("error serializing", e);
      throw (new RuntimeException("Error serializing", e));
    }

deserialization:

try (final Input input = new Input(inputStream)) {
      return ((Serializable) kryo.readObject(input, entityType));
    }

entityType is the parent class, in this case: shell.api.model.Heartbeat

and, inside Heartbeat are several entities, one of which is BatteryStatus.

Kryo can handle serializing and deserializing complex nested objects and circular references. It's part of the reason why so many people love Kryo!

Since the object you are sending could be one of many possible types you should use the writeClassAndObject and readClassAndObject methods.

protected final Kryo kryo = new Kryo();

try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    try (final Output output = new Output(baos)) {
      kryo.writeClassAndObject(output, data);
      return (baos.toByteArray());
    } catch (IOException e) {
      LOGGER.error("error serializing", e);
      throw (new RuntimeException("Error serializing", e));
    }

And

try (final Input input = new Input(inputStream)) {
  return ((Serializable) kryo.readClassAndObject(input));
}

Docs here

One other possibility is you are using two different versions of Kryo jar in your project and different version classes are being used in serialization and deserialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM