我具有以下内容:类BaseModel包含BaseForm:

public class BaseModel {
    BaseForm form;

    public BaseForm getForm() { return form; }
    public void setForm(BaseForm form) { this.form = form; }
}


MyModel类扩展BaseModel; MyForm类扩展BaseForm。换句话说,存在并行继承,


  我的模型-> BaseModel
  
  MyForm-> BaseForm


public class MyModel extends BaseModel {
    // ... 'form' (inner data member) is set to MyForm which extends BaseForm
}


下面给了我一个ClassCaseException。我需要接收此特定模型中包含的特定表格:

MyForm myForm = (MyForm)specificModel.getForm();



  java.lang.ClassCastException:无法将BaseForm强制转换为MyForm


我了解到我无法参加特定的课程,但是我该怎么办?

最佳答案

如果您在form中设置为成员MyModel的对象实际上是MyForm(而不是BaseForm),则不会引发异常。请参见下面的示例(我已经测试了代码):

public class MyModel extends BaseModel {

    // ... 'form' (inner data member) is set to MyForm which extends BaseForm
    MyModel(MyForm mf) {
        this.form = mf;
    }

    public static void main(String[] args) {
        MyForm mf = new MyForm();
        MyModel specificModel = new MyModel(mf);
        MyForm myForm = (MyForm) specificModel.getForm();  // No exception now
    }
}

public class BaseModel {
    BaseForm form;

    public BaseForm getForm() { return form; }
    public void setForm(BaseForm form) { this.form = form; }
}

public class MyForm extends BaseForm {
}

public class BaseForm {
}

07-26 05:22