检查 Java 中对象的子类

Check subclass of an object in Java

考虑 类 MinorClassAMinorClassB,它们都扩展了 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 a ClassCastException. Otherwise the result is false.

所以在你的情况下:

if (obj instanceof MinorClassA) {
    ...
}

使用 instanceof 检查 obj 是否是 Class:

的一个实例
if (obj instanceof MinorClassA) {
   System.out.println("obj is an instance of MinorClassA");
} else if (obj instanceof MinorClassB) {
   System.out.println("obj is an instance of MinorClassB");
}