如何从基类实例中找出子类? [英] How to find out the subclass from the base class instance?

查看:98
本文介绍了如何从基类实例中找出子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从基类实例中找出派生类的名称?

Is there a way to find out the name of derived class from a base class instance?

例如:

class A{
    ....
}
class B extends A{
    ...
}
class c extends A{
    ...
}

现在如果一个方法返回一个 A 的对象,我可以看出它是 B 还是 C

now if a method returns an object of A, can I find out if it is of type B or C?

推荐答案

使用 instanceof Class#getClass()

A returned = getA();

if (returned instanceof B) { .. }
else if (returned instanceof C) { .. }

getClass()将返回以下任一项: A.class B.class C.class

getClass() would return either of: A.class, B.class, C.class

if-clause你需要向下转换 - 即

Inside the if-clause you'd need to downcast - i.e.

((B) returned).doSomethingSpecificToB();






这就是说,有时它被视为使用 instanceof getClass()是一种不好的做法。您应该使用多态性来尝试避免检查具体子类,但我可以'请告诉您更多信息。


That said, sometimes it is considered that using instanceof or getClass() is a bad practice. You should use polymorphism to try to avoid the need to check for the concrete subclass, but I can't tell you more with the information given.

这篇关于如何从基类实例中找出子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆