Casting an object to its original type

I am trying to send Collection<myClass>over the network. I passed it as an object, and I sent it that way.

I think that the best way to simulate an element being transmitted over the network is through Object, since I don’t know in advance what it can be (in this example it’s a collection, but sometimes it’s a map or any other thing you can think of) . This would be somewhat similar to the way sockets work in C, where only the receiver and sender know what they are sending / receiving, and appropriately allocate objects, while the connection takes care of only the bytes and transfers them properly.

However, upon receiving the object, if I try to return it back to collection<myObject>, the warning indicates unsafe type casting. I could add @suppressWarnings, but what would be the best way to do this to avoid this warning?

thank

+5
source share
2 answers

Since you (although mostly Java) do not know the type of object you are getting, it cannot be safely discarded.

What can you do:

  • You need to be sure that this is the object that you consider it to be.
  • Perhaps add a block try-catchto catch ClassCastException(to be sure)
  • Finally, add an annotation @SuppressWarningsas you want to override Java security checks (because you think you know better).
+3
source

, JSON XML. / JSON. GSON. , , , .

+1

All Articles