Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting based on a variable not an object name.

 
Mr Murdstone
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic