File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When use instanceof when use .isAssignableFrom?

 
Robert Paris
Ranch Hand
Posts: 585
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Robert Paris
Ranch Hand
Posts: 585
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 585
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whoops, yes I meant "obj.getClass()" in the check there.
Thanks for the help!
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic