Java将Type作为参数传递给期望子类型

时间:2016-04-29 13:16:01

标签: java generics subtype generalization

我是Java新手,我尝试制作一些非常简单的Java应用程序。在我的尝试中,我遇到了泛化的问题。我有一个 Person 对象列表。 可以是母亲

然后,我有几个同名的方法吃(...),但它们的输入参数不同。这些方法不是 Person 类的一部分。其中一种方法接受 Mother 作为参数,另一种接受

问题是如何动态决定在 Person 列表中调用哪个方法。当我尝试遍历列表并调用 o.eat(iterator)时,它会提示编译错误,因为迭代器的类型为 Person 但我的方法希望母亲父亲作为参数。编译器不知道我有每种类型的 Person

的方法

到目前为止,我已经用 if 语句解决了我的问题,其中我通过 GetType()方法将类类型与母亲进行比较如果等于我可以将 Person 转换为适当的类型。

代码如下所示:

  if (person.getClass().equals(Father.class)) {
            theView.eat((Father) person);
        }


  if (person.getClass().equals(Mother.class)) {
            theView.eat((Mother) person);
        }

吃法方法如下:

 public void eat(Mother m){
    textArea.append(m.breakfast);
    textArea.append(m.lunch);
    textArea.append(m.dinner);
 }
午餐晚餐和早餐只是一些字符串,表明这个人正在做什么

person是代码是通过Person对象列表的迭代器

有没有更好的解决方案可以自动化过程?

提前谢谢。

3 个答案:

答案 0 :(得分:1)

使用多态:

public interface Person{
    void eat();
}

public class Mother implements Person{

    @Override
    public void eat()
    {
        //the code inside eat(Mother) goes here
    }

}

public class Father implements Person{

    @Override
    public void eat()
    {
        //the code inside eat(Father) goes here
    }

}

然后,只需在Person列表的每个对象上调用eat方法:

for(final Person person: personList){
    person.eat();
}

答案 1 :(得分:1)

  

然后,我有几个同名的方法吃(...),但它们的输入参数不同

如果您的类使用不同的{FALSE,FALSE,0.25,0.25,0.25,0.25,FALSE,FALSE,FALSE}方法实现如下:

eat

现在你的迭代方法可以实现如下:

public class TheView<T extends Person> {
    public void eat(T t) {
         textArea.append(t.getMeals());
    }
}

您的列表可以包含任意数量的public <T> void yourMethod(List<? extends Person> personList) { for (Person p : personList) { theView.eat(p); } } Father个对象,只要它们实现/扩展Mother类,

Person

答案 2 :(得分:0)

我认为你需要访客模式,因为你在这里说了什么

  

问题是如何动态决定调用哪个方法   人员名单。

https://api.jquery.com/jquery.get/

这有助于您确定在运行时动态采用哪条路线

来自维基百科:https://sourcemaking.com/design_patterns/visitor/java/2

  

double dispatch是多个dispatch的一种特殊形式,和   将函数调用分派给不同的具体的机制   函数取决于所涉及的两个对象的运行时类型   电话。