I'm trying to send a Collection<myClass>
across a network. I cast it as an Object, and I sent it this way.
I think the best way to modelize the item being passed in the network is through an Object, since I don't know in advance what it might be (in this example, it's a Collection, but some other times it's a Map or any other thing you can think of). This would be somehow like the way sockets work in C, where only the receiver and sender know what they're sending/receiving, and cast the objects appropriately, whereas the connection only cares about bytes and transmitting them properly.
However, when receiving the Object, if I try to cast it back to collection<myObject>
, a warning mentions unsafe type casting. I could add @suppressWarnings, but what would be the best way to do this cast so as to avoid this warning ?
Thanks
As you (although, mostly Java) do not know the type of the object that you receive, it is impossible to safely cast it.
Thing you can do:
try-catch
block to catch ClassCastException
(to be extra sure)@SuppressWarnings
annotation, as you want to override the safety checks of Java (because you think to know better)Consider using some intermediate format for serialization, like JSON or XML. There are plenty of libraries out there for marshalling and unmarshallling objects into/from JSON. For instance GSON. What you get for free is the language interoperability, because on the other hand of the wire there could be a program in any language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With