考虑类 MinorClassA
和MinorClassB
,都延伸MajorClass
。我有一个对象 MajorClass
我确信它实际上是其子类之一的实例。
MinorClassA subclassedObj = new MinorClassA();
MajorClass obj = subclassedObj;
//------ More code -------------
if( subclassof(obj) == MinorClassA) //Something like this
如何找出该对象的子类是什么?我无权访问 subclassedObj
,仅限obj
.
编辑澄清:我知道如何检查是否 MinorClassA
是 MajorClass
的实例,但反之则不然。
最佳答案
听起来你想要 instanceof
operator:
At run time, the result of the
instanceof
operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result is false.
所以在你的情况下:
if (obj instanceof MinorClassA) {
...
}
关于java - 检查Java中对象的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620277/