这是尝试过的代码。
public class ChildB extends BaseA {
public void showMessage() {
Log.d("myTest", "Here is ChildB.");
}
}
public class ChildC extends BaseA {
public void showMessage() {
Log.d("myTest", "Here is ChildC.");
}
}
public class NormalD {
public void showMessage() {
Log.d("myTest", "Here is NormalD.");
}
}
public class BaseA {
public void showMessage(String sSpecifiedChild) {
sSpecifiedChild.showMessage(); <== I'd like to invoke a child method specified by String value.
}
}
public class MainActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jelly_notification);
BaseA baseA = new BaseA();
baseA.showMessage("ChildC");
baseA.showMessage("ChildB");
baseA.showMessage("NormalD"); <== occurs an exception because "NormalD" is not child of BaseA.
}
}
期望的结果是:
这是ChildC。
这是ChildB。
它发生了NormalD的例外。
答案 0 :(得分:1)
您可以使用基类中的某个类或@class属性参数来强制转换对象。使用该属性准备对象,对于任何派生类,您可以使用相同的函数,它将调用。你可以have a look at it