在不知道对象的实际类型的情况下填充对象

时间:2016-06-24 14:18:49

标签: java

我的代码有问题:我有一些类实现了这样的接口:

public interface MyInterface{
puclic void myMethod{...}
}

public class Class1 implements MyInterface{
private int choice1;
private String choice2;
(Override of the other method define in interface)
}

public class Class2 implements MyInterface{
private String choice1;
private int choice2;
(Override of the other method define in interface)
}

这些类在我的模型中,我想请求视图单独选择这些类中的每个参数,并将模型中的视图从一个视图保存到一个,但我必须使用我的控制器来验证输入。 问题是在控制器中我不知道对象的类型,所以我不能调用特定方法获取或设置。此外,我无法在界面中编写它,因为我在Class1和Class2中有不同的参数。 因此,我不知道如何从模型中的视图中保存选择。

1 个答案:

答案 0 :(得分:2)

将保存逻辑放在Class1和Class2中。让他们保存他们的值,或者至少让他们产生一些String,List等,视图可以保存对具体对象的不可知。总结一下,我建议在接口上添加一个方法save(),它可以保存状态或以一种可以保存的方式返回状态。