Links

Lists

Latest Updates

Ruby On Rails List
Python list
Advanced Java
The JavaScript List
Apache Users
Full Disclosure
Linux Security

Search the archives!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Advanced-java] BAsic class question


  • From: justin@xxxxxxxxxx (Justin Couch)
  • Subject: [Advanced-java] BAsic class question
  • Date: Wed, 27 Feb 2002 19:53:57 +1100

Sybille Breunig wrote:
> Why don't you use :
> if (obj instanceof X)
>     // do anything

Because that will always evaluate to false in this case. instanceof is a 
runtime operator that acts on the class. If you have a variable of type 
Class then having some random object checking for the class won't work.

void checker(Object blah) {
   Class myClass = foo.class;

   if(blah instanceof myClass)
      ///
}

This will not compile. The RHS of instanceof must be a name of a class, 
not the Class object. If you want to check that two objects are of the 
same class, when one of those objects is expressed in terms of an 
instance of java.lang.Class, the only way you can do it is through the 
isInstance() method. This will check for any object being of the same 
class type. ie, it evaluates to the equivalent of

void checker(Object blah) {
   Class myClass = foo.class;

   if(myClass.equals(blah.getClass())
      ///
}

-- 
Justin Couch                         http://www.vlc.com.au/~justin/
Java Architect & Bit Twiddler              http://www.yumetech.com/
Author, Java 3D FAQ Maintainer                  http://www.j3d.org/
-------------------------------------------------------------------
"Humanism is dead. Animals think, feel; so do machines now.
Neither man nor woman is the measure of all things. Every organism
processes data according to its domain, its environment; you, with
all your brains, would be useless in a mouse's universe..."
                                               - Greg Bear, Slant
-------------------------------------------------------------------