gpt4 book ai didi

java - 检查Java中对象的子类

转载 作者:行者123 更新时间:2023-12-02 11:21:11 27 4
gpt4 key购买 nike

考虑类 MinorClassAMinorClassB ,都延伸MajorClass 。我有一个对象 MajorClass我确信它实际上是其子类之一的实例。

MinorClassA subclassedObj = new MinorClassA();
MajorClass obj = subclassedObj;

//------ More code -------------

if( subclassof(obj) == MinorClassA) //Something like this

如何找出该对象的子类是什么?我无权访问 subclassedObj ,仅限obj .

编辑澄清:我知道如何检查是否 MinorClassAMajorClass 的实例,但反之则不然。

最佳答案

听起来你想要 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) {
...
}

关于java - 检查Java中对象的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620277/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com