从父母那里获得孩子的班级名称 [英] Get child class name from parent
问题描述
我有一个我自己的所有活动(ActivityBase
)的基类,而这些活动本身是从android.app.Activity
派生的.在onCreate中,我想基于当前正在执行的子类执行一些条件逻辑.如果SomeCustomActivity
和AnotherCustomActivity
都扩展了ActivityBase
,如何在父类(ActivityBase
)中确定当前执行的是哪两个?
I have a base class for my all of activities (ActivityBase
) that itself derives from android.app.Activity
. In onCreate I want to execute some conditional logic based on the currently executing child class. If SomeCustomActivity
and AnotherCustomActivity
both extend ActivityBase
, how can I determine in the parent class (ActivityBase
) which of the two is the currently executing one?
推荐答案
使用 instanceof 运算符.
假设您有一个基类和两个名为Base
,SubOne
和SubTwo
的子类,如果要检查变量ref
是SubOne
还是SubTwo
的实例,说:
Supposing you have a base class and two subclasses named Base
, SubOne
and SubTwo
, if you want to check if a variable ref
is an instance of SubOne
or SubTwo
you'd say:
if(ref instanceof SubOne){
}
else if(ref instanceof SubTwo){
}
请注意:尽管(ref instanceof Base)
始终会返回true
.
Note that: (ref instanceof Base)
will always return true
though.
这篇关于从父母那里获得孩子的班级名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!