Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast of object into original type

Tags:

java

casting

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

like image 970
shkra19 Avatar asked Oct 05 '22 05:10

shkra19


2 Answers

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:

  • You need to be really sure it is the object you think it is
  • Maybe add a try-catch block to catch ClassCastException (to be extra sure)
  • And finally add the @SuppressWarnings annotation, as you want to override the safety checks of Java (because you think to know better)
like image 161
Veger Avatar answered Oct 12 '22 02:10

Veger


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.

like image 44
Jiri Kremser Avatar answered Oct 12 '22 01:10

Jiri Kremser