Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic casting 1

Status
Not open for further replies.

RogerFGay

Programmer
Jun 22, 2001
49
0
0
SE
It seems so obvious. I send various types of objects through an object stream. When they get to the other side, they are read as Object obj = in.readObject() : type Object. I can easily get the name of the original class type via obj.getClass().getName()

Now what I want is a very simple way of casting back to the original class type so that I can use overloaded handlers - i.e. one handler for each type that this application may receive. I've tried all day, but still can't find anything that works. Here's one thing I've tried.

try {
process2Input(obj.getClass().cast(Class.forName(rtm.getClass().getName())));
} catch (ClassNotFoundException e) {
}

As with other things, it still thinks it's Object class rather than its original class, which is given by getName()

 
As cpjust says, it is rarely a good idea to have the state of a class open to direct outside manipulation. In such a situation, the code you write inside the class can't know if something outside has changed the state. And it would be a nightmare for multithreaded applications since any external access to this state would need to be synchronized ... externally.

A good rule of thumb is to have as little of a class's state available to outside influence as possible, and when it is necessary, do so through accessor methods such as get and set. That way, the class has more control over its state, and can also synchronise access to it if required in a multithreaded environment.

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top