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

Checking an Object before you cast

Status
Not open for further replies.

riches85

Programmer
Nov 13, 2002
59
US
I have a JTree that stores 1 of two different classes as objects in each DefaulyMutableTreeNode. Is it possible to check if casting the object to another class would raise an exception before I cast it. For example:

if( casting to string is valid )
String string = (String)myObject;
 
Code:
  Object o = new String("abc");
  boolean isString = o.getClass().getName().equals("java.lang.String");
  if (isString) {
     String s = (String)o;
  } else {
   // do something else
  }
 
Code:
  Object o = new String("abc");
  [b]if (o instanceof String) {[/b]
    String s = (String)o;
  } else {
  // do something else
 }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top