开发者

How can I get the most specific class of an instance?

开发者 https://www.devze.com 2023-04-05 07:01 出处:网络
Supp开发者_如何学Goose I have the following classes: class A {} class B extends A {} A instA = new A();

Supp开发者_如何学Goose I have the following classes:

class A {}
class B extends A {}

A instA = new A();
A instB = new B();

Now as far Java is concerned instB is of type A.

How can I find out what is instB's actual type?


You can use instB.getClass(). This will return a Class object representing instB's runtime type.

Source: javadoc

You can also use the following conditional check with instanceof:

if (instB instanceof B) {
    //then we know it is of type B
}

instanceof would be the more conventional way, and the conditional will also return true if instB is a subclass of B.

You may want to further explain your use case, with code examples, to get better discussion.


For compile-time, I do not know of any possibility. It is not easy, because it is control flow dependent (looking at the declaration is not sufficient). But when you wrote the declaration, you decided that you only need the class-A-interface/behavior of instB.

For run-time, you can use getClass(), instanceof, as Kublai suggested. But again, you should not need it in most of the cases: With a good design of your classes, you can let dynamic dispatch make the case distinctions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号