Ric*_*ich 29 java inheritance android
我有一个基类,用于我ActivityBase自己派生的所有活动()android.app.Activity.在onCreate中,我想基于当前正在执行的子类执行一些条件逻辑.如果SomeCustomActivity和AnotherCustomActivity两者都扩展ActivityBase,我如何在父类(ActivityBase)中确定哪两个是当前正在执行的?
One*_*rld 68
在某些情况下,父类中的这一行只能解决这个问题.它返回"child"类的名称(不是父类):
this.getClass().getName() //String like "com.mycompany.myclassname"
this.getClass().getSimpleName() //String like "myclassname"
Run Code Online (Sandbox Code Playgroud)
有关进一步的讨论,请参见此处:http://www.coderanch.com/t/324715/java/java/Getting-child-class-name-parent
Sam*_*muh 18
使用instanceof运算符.
假设您有一个基类和两个已命名的子类Base,SubOne并且SubTwo,如果您想检查变量ref是否是您的实例,SubOne或者SubTwo您要说:
if(ref instanceof SubOne){
}
else if(ref instanceof SubTwo){
}
Run Code Online (Sandbox Code Playgroud)
请注意:虽然(ref instanceof Base)会一直返回true.