Always Check Type Before Cast

 class​ Network {
 
  ObjectInputStream inputStream;
  InterCom interCom;
 
 void​ listen() ​throws​ IOException, ClassNotFoundException {
 while​ (​true​) {
  Object signal = inputStream.readObject();
» CrewMessage crewMessage = (CrewMessage) signal;
  interCom.broadcast(crewMessage);
  }
  }
 }

Sometimes, you have to deal with dynamic object types at runtime. Dynamic objects can come from various sources, typically when serialized Java objects are exchanged through a channel. Before being able to use them in your program, you’ll need to explicitly cast them to a type. If you don’t do this properly, your program could crash with some kind of a RuntimeException.

In the code above, you can see a class that reads ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.