简体   繁体   中英

Java - Is it possible to read a serialized object without casting?

I am reading objects from a serialized file and I really do not like the fact that I have to cast the result eg

vars = (HashMap<String, Integer>) out.readObject();

Being a fan of type information as I loathe the cast. Is it possible to avoid it and tell explicitly what type should be read from a serialized file?

ObjectInputStream is not a generic type, and does not provide generic methods.

There are specific methods for read[primitive] provided, but for actual objects, only readObject is provided - which returns Object .

Of course, if you don't need to use Java's own Serializable or Externalizable interfaces and would rather serialize with specific frameworks (eg Jackson), you may avail of methods that do not require explicit downcasting upon de-serialization.

Note

ObjectInputStream is not final , and you can extend it to provide your own implementation, which could allow you to provide a generic class or method and prevent casting when invoking some readTypedObject method of your own.

You could then compare readClassDescriptor() with a Class<T> you initialized your own ObjectInputStream implementation with, in order to make sure the object that is being read can be assigned to your parametrized type.

However, you'd end up casting to T at some point anyway, since you probably don't want to override readObject too!

TL;DR, way too much effort and complication in my opinion, I'd just go with casting at the receiver end.

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