This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes When use instanceof when use .isAssignableFrom? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When use instanceof when use .isAssignableFrom?" Watch "When use instanceof when use .isAssignableFrom?" New topic
Author

When use instanceof when use .isAssignableFrom?

Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Why, when I'm checking an Object returned from a method, would I use:
if ( ServiceInfo.class.isAssignableFrom( obj ) )
instead of using:
if ( obj instanceof ServiceInfo )
What is the benefit of one over the other? Don't they do the same thing?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
They're not the same. The isAssignableFrom() method expects its argument to be an instance of the Class class (or the class Class if you prefer :roll: ). So

could be replaced with

if you really wanted to - but the latter is longer and slower; what's the point? The isAssignableFrom() method is useful if you already have a Class object representing the class you want to inquire about, but not instance of that class. Or if, at compile time, you don't know the name of the class(es) you wish to learn about (at runtime). The instanceof operator must be followed by a known class or interface name at compile time - if you don't know that, you can't use it.
[ August 13, 2002: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Ah! So then I could do something like this:
1. Have an XML config:
<Node ClassInstanceCheck="com.mycomp.Test" />
2. Have code like:
Class cl = Class.forName( config.get( "ClassInstanceCheck" ) );
if ( cl.isAssignableFrom( obj ) )
....
(If the above code is valid, then I see the benefit!)
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yes, except that "obj" must be a Class instance also. If it isn't, then use obj.getClass() to get the associated class instance.
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
whoops, yes I meant "obj.getClass()" in the check there.
Thanks for the help!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When use instanceof when use .isAssignableFrom?
 
Similar Threads
determining an object class is an array, list etc
instanceof
instanceof prblem help me
equals();
compare object