Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

oop - Is there a way to determine what type a class is an instance of in Java?

Say I have 3 classes like so:

class A {}
class B extends A {}
class C extends A {}

Would it then be possible to determine whether a particular object was an instance of A, B, or C?

I thought that something like this might work:

if (myObject.getClass().isInstance(B.class)) {
    // do something for B
} else (myObject.getClass().isInstance(C.class)) {
    // do something for C
} else {
    // do something for A
}

but after reading a little I think it would always evaluate as B since it's just testing if a cast would work and there's no substantial differences between them.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simpler and faster code is:

if (myObject instanceof B) {
} else if (myObject instanceof C) {
} else if (myObject instanceof A) {
}

Note that the order is important: you have to have the test for A last, as that will succeed for instances of B and C as well.

However, your original code would nearly work. Class.isInstance checks whether the value really is an instance of the given class or any superclass. So if myObject is an instance of C, then B.class.isInstance(myObject) will return false. All you've got wrong is that you're calling getClass() on myObject unnecessarily, instead of using B.class etc.

This is the approach you would take if you didn't know which classes you were interested in at compile time - the instanceof operator only works when you can specify the type statically in code.

Now if you want to find out whether myObject is an instance of exactly B (and not a subclass) then just use:

if (myObject.getClass() == B.class)

(This will blow up if myObject is a null reference, of course.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...