• Post Reply Bookmark Topic Watch Topic
  • New Topic

java.lang.Class - isAssignableFrom/isInstance redundant ?  RSS feed

 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to determine criteria for determining whether to use the method java.lang.Class#isAssignableFrom(java.lang.Class) instead of java.lang.Class#inInstance(java.lang.Object).

Specifically, I can't think of a reason why together, they are not redundant. I can't imagine why the body of the isInstance method couldn't look something like this:



The following sample program outputs two boolean values. I can't think of a scenario where it would output two different boolean values - that is, it outputs "true true" or "false false" always.
I would love to be corrected.

 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The javadocs are pretty clear on the distinction between the two:

isInstance(Object obj) is the dynamic equivalent of the Java language instanceof operator.

isAssignableFrom(Class cls) tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even so, how are they functionally unique ?
The javadocs use differing terminology sure, but I don't see how that answers the question.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tony Morris:
Even so, how are they functionally unique ?


One operates on Class objects, and one operates on Objects; i.e., isInstance() requires you to have an object to call it on, and isAssignableFrom() doesn't. Furthermore, isAssignableFrom() can answer more specific questions about interfaces and classes: does this class implement this interface? Does this interface extend this class?

I think you're probably right, though, that

aClass.isInstance(anObject)

is just a shorthand for

aClass.isAssignableFrom(anObject.getClass())
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!