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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Casting Issue

Status
Not open for further replies.

jsulman

Programmer
Jun 14, 2001
85
US
Is there any way to cast an object based on a variable and not the actual object type?
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.
 
I think you've got it all a bit muddled up.
Assuming that "State" is an interface, an abstract class, or that "Texas" extends "State", you would do :

Code:
public void test(State state) {
  if (state instanceof Texas) {
     Texas tx = (Texas)state;
  }
}

or, as maybe you are getting at :

Code:
public void test(Texas tx) {
  // no need to cast, because Texas implements/extends State
  State state = tx;
}

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top