Article View: borland.public.jbuilder.java.api
Article #1030Re: proper/suggested way to compare if one class is an instance of another?
From: Owen
Date: Wed, 01 May 2002 01:09
Date: Wed, 01 May 2002 01:09
29 lines
2092 bytes
2092 bytes
"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:
<3ccf3edb_1@dnews>Path:
arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-03!supernews.com!194.159.246.34.MISMATCH!kibo.news.demon.net!demon!peernews!peer.cwci.net!news4-gui.server.ntli.net!ntli.net!newsfeed01.sul.t-online.de!t-online.de!dnewsReferences:
<3ccebd9c_2@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-04-30 18:09:22 PST From: "Owen" <owen@begonefoulmachine.kennulz.demon.co.uk> Newsgroups: borland.public.jbuilder.java.api References: <3ccebd9c_2@dnews> Subject: Re: proper/suggested way to compare if one class is an instance of another? Date: Wed, 1 May 2002 02:09:29 +0100 Lines: 36 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 5.50.4522.1200 X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4522.1200 NNTP-Posting-Host: 217.135.5.239 Message-ID: <3ccf3edb_1@dnews> X-Trace: dnews 1020215003 217.135.5.239 (30 Apr 2002 18:03:23 -0700) Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-03!supernews.com!194.159.246.34.MISMATCH!kibo.news.demon.net!demon!peernews!peer.cwci.net!news4-gui.server.ntli.net!ntli.net!newsfeed01.sul.t-online.de!t-online.de!dnews