wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Casting based on a variable not an object name. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting based on a variable not an object name." Watch "Casting based on a variable not an object name." New topic
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???
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting based on a variable not an object name.
 
Similar Threads
please help "javax.servlet.jsp.JspException: Failed to obtain specified collection"
problem with bean
When submiting driop down value its shwoing null.
s:select and data conversion
Need Some Help with a Program