java – 两种不同的参数类型(将Object强制转换为Type)

我想调用一个方法,但参数可以是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
    } 
}
点赞