我想调用一个方法,但参数可以是 Button 或 ImageButton。我使用不同的参数类型作为对象调用该方法两次。
在我的方法 attributesOfButton 中,我想像下面的代码一样分配相应的按钮类型。
private void memCheck()
{
ImageButton imageButtonCam;
Button buttonCamCo;
attributesOfButton(imageButtonCam);
attributesOfButton(buttonCamCo);
}
private void attributesOfButton(Object button)
{
Object currentButton;
if (button instanceof ImageButton)
{
currentButton = (ImageButton) button;
}
if (button instanceof Button )
{
currentButton = (Button) button;
}
// do something with button like:
if (Provider.getValue == 1) {
currentButton.setEnabled(true);
}
}
但它不起作用。例如,如果我这样做:
currentButton.setEnabled(true);
我明白了
Cannot resolve method setEnabled(boolean)
最佳答案
您的对象 currentButton 仍被定义为 Object,因此即使您知道它是一个子类,您也不能在其上使用 Object 的方法以外的任何东西。您需要使用适当的类定义一个对象:
private void attributesOfButton(Object button)
{
if (button instanceof ImageButton)
{
ImageButton currentButton = (ImageButton) button;
// do stuff for ImageButton
}
if (button instanceof Button )
{
Button currentButton = (Button) button;
// do stuff for Button
}
}
关于java - 两种不同的参数类型(将对象转换为类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803721/