| Author |
Casting based on a variable not an object name.
|
Mr Murdstone
Greenhorn
Joined: Sep 02, 2004
Posts: 1
|
|
Is there any way to cast an object based on a variable and not the actual object name? For example I know I can do this: public class testCast(Texas tx){ // Texas extends State State state = null; State = (Texas)tx; } What if I had an object of Texas but did not know the name of the class but had it in a variable instead? public class testCast2(Texas tx){ State state = null; stateName = tx.getClass().getName(); State = (stateName)tx } How would I do the equivalent of State = (stateName)tx where stateName is a String containing the name of the class. Thank you in advance Jeff Sulman
|
 |
Steve Morrow
Ranch Hand
Joined: May 22, 2003
Posts: 657
|
|
What if I had an object of Texas but did not know the name of the class but had it in a variable instead? public class testCast2(Texas tx){ State state = null; stateName = tx.getClass().getName(); State = (stateName)tx } How would I do the equivalent of State = (stateName)tx where stateName is a String containing the name of the class.
First, writing methods that depend on a particular subtype of the passed reference should be a big huge red flag for you to rethink your design. Second, if Texas extends State, casting is unnecessary, to wit:I get the feeling this is not what you're asking about though. Can you describe more specifically what it is you're trying to do? Do you have a concrete example?
|
 |
Steve Morrow
Ranch Hand
Joined: May 22, 2003
Posts: 657
|
|
Also... Because of type compatibility rules in Java "upcasting" is unnecessary. Example: Hope this helps. Let us know if you have more questions.
|
 |
Timmy Marks
Ranch Hand
Joined: Dec 01, 2003
Posts: 226
|
|
I don't know if it would be possible or not, but before we get into that, what would you gain by doing so? To put it another way, if you don't know into which subclass you are going to cast the instance, how do you know which subclass-specific methods will be available???
|
 |
 |
|
|
subject: Casting based on a variable not an object name.
|
|
|