🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.java.programmer
Article #331

Re: Bug in Class class?????

#331
From: Pete Cockerell
Date: Sat, 29 Nov 1997 00:00
65 lines
2545 bytes
I'm not sure that you've wholly grasped what isInstance() does. The
argument is an instance of Object (not of class Class), and the
function returns true if the argument is an instance of the receiver
Class object, or one of its subclasses. In your example, you'll never
get 'true' because your arguments are all of class Class. What you
want is:

     System.out.println(b.class.isInstance(new a()));
     System.out.println(a.class.isInstance(new a1()));
     System.out.println(b.class.isInstance(new a1()));

If you think about it, there would be no need for a function to
provide the information you're asking for, because it's statically
determined by the class hierachy. For example, this would return true:

     System.out.println(Class.class.isInstance(a.class));

but everything in that expression is knowable at compile time, so it's
just the same as saying

     System.out.println(a.class instanceof Class);

isInstance() is designed to return information about the dynamic class
of instances, which are typically referenced by variables of some
high-up superclass, e.g. Object. Though of course, in general, asking
an object if it's an instance of a particular class is a Bad Thing and
leads to fragile code.

Cheers,
Pete

Carl Hewitt wrote:
> 
> The isInstance method of the Class class does not seem to work (as does the
> getClasses() and getDeclaredClasses()  The following code returns false
> for all three statements)
> 
> TIA
> 
> Carl
> 
> public class MyClass1 {
>   public static void main(String[] args) {
>     System.out.println(b.class.isInstance(a.class));
>     System.out.println(a.class.isInstance(a1.class));
>     System.out.println(b.class.isInstance(a1.class));
>   }
> }
> 
> class a implements a1 {
> 
> }
> 
> class b extends a {
> 
> }
> 
> interface a1 {
> 
> }

-- 
Pete Cockerell
California, USA
Technical Details
Message-ID: <348079EB.1ADB4302@best.com>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <34801D17.4EA42334@oop.com>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 10a146,2efc8c35cff1956f
X-Google-Attributes: gid10a146,public
X-Google-Thread: 1089d0,2efc8c35cff1956f
X-Google-Attributes: gid1089d0,public
X-Google-Thread: f74b3,2efc8c35cff1956f
X-Google-Attributes: gidf74b3,public
From: Pete Cockerell <petec@best.com>
Subject: Re: Bug in Class class?????
Date: 1997/11/29
Message-ID: <348079EB.1ADB4302@best.com>
X-Deja-AN: 293718739
References: <34801D17.4EA42334@oop.com>
X-Trace: 880835134 8811 (none) 206.86.0.12
Newsgroups: comp.lang.java.programmer,borland.public.jbuilder.java.language,borland.public.jbuilder.java.api