简体   繁体   English

如何获得实例的最特定类?

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

Suppose 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. 现在,就Java而言,instB是A类型的。

How can I find out what is instB's actual type? 我如何找出instB的实际类型?

You can use instB.getClass() . 您可以使用instB.getClass() This will return a Class object representing instB 's runtime type. 这将返回一个代表instB的运行时类型的Class对象。

Source: javadoc 资料来源: javadoc

You can also use the following conditional check with instanceof : 您还可以对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 . instanceof是更常规的方式,如果instBB的子类,则条件instB也将返回true。

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. 但是,当您编写声明时,您决定只需要instB的A类接口/行为。

For run-time , you can use getClass() , instanceof , as Kublai suggested. 对于运行时 ,可以使用Kublai建议的getClass()instanceof 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. 但是,在大多数情况下,您都不需要它:通过对类进行良好的设计,可以让动态分派区分大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM