Article View: borland.public.jbuilder.java.api
Article #1037Re: proper/suggested way to compare if one class is an instance of another?
From: PeterH
Date: Wed, 01 May 2002 14:55
Date: Wed, 01 May 2002 14:55
47 lines
2281 bytes
2281 bytes
Thank you for your notes! I have a bit to decide for our code with this. Thanks again. "Owen" <owen@begonefoulmachine.kennulz.demon.co.uk> wrote in message news:3ccf3edb_1@dnews... > > "PeterH" <!REMOVEBeforeSending!peter@pchenry.com> wrote in message > news:3ccebd9c_2@dnews... > > What is the proper or suggested way to compare if one class is of another > > type/class? > > > > Should the .getClass() be used to compare it with the .class? Or should > the > > instanceof keyword be used? > > > A straight comparison of getClass() will work only of you're inetersted in > comparing whether two objects have exactly the same concrete (i.e. > implmentation) class (and were loaded by the same classloader? This rings a > bell...). > > a instanceof b will return true if the object under inspection (a) can be > cast to the class in question (b) without a ClassCastException ocurring, so > will work with if a's class derives from b. > > You could also use Class.isInstance() to test whether a given object is of a > class whose type is not necessarily known at compile time, which is useful > for dynamic class loading situations. > > Be aware that none of these things are paricularly speedy, and that by and > large avoiding this sort of class comparison in favour of polymorphism is > preferable where possible. > > hth > Owen > > > > > > >
Technical Details
Message-ID:
<3cd001c6_2@dnews>Path:
arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!supernews.com!cox.net!nntp-relay.ihug.net!newsfeeds.ihug.co.nz!ihug.co.nz!dnewsReferences:
<3ccebd9c_2@dnews> <3ccf3edb_1@dnews>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 1089d0,4bc02a730daffc47 X-Google-Attributes: gid1089d0,public X-Google-ArrivalTime: 2002-05-01 08:05:13 PST From: "PeterH" <!REMOVEBeforeSending!peter@pchenry.com> Newsgroups: borland.public.jbuilder.java.api References: <3ccebd9c_2@dnews> <3ccf3edb_1@dnews> Subject: Re: proper/suggested way to compare if one class is an instance of another? Date: Wed, 1 May 2002 10:55:05 -0400 Lines: 49 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2600.0000 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000 NNTP-Posting-Host: 66.46.195.190 Message-ID: <3cd001c6_2@dnews> X-Trace: dnews 1020264902 66.46.195.190 (1 May 2002 07:55:02 -0700) Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!supernews.com!cox.net!nntp-relay.ihug.net!newsfeeds.ihug.co.nz!ihug.co.nz!dnews