简体   繁体   English

Java从父类中检索子类对象

[英]Java Retrieve Subclass Objects from Parent Class

Is it possible to write a method which allows me to take in a List of objects belonging to a Parent class Person . 是否可以编写一个方法,允许我接受属于父类Person的对象列表。

Under Person class, there are several subclasses, which includes Employee class. Person类下,有几个子类,包括Employee类。

I want the method to return a separate List which consists of just the Employee objects from the original list. 我希望该方法返回一个单独的List,该List仅包含原始列表中的Employee对象。

Thank you 谢谢

You need to do it by steps : 您需要按步骤执行:

  1. Iterate on the List<Person to check all of them 迭代List<Person来检查所有这些
  2. If the current element is en Employee you need to cast it as and keep it 如果当前元素是Employee ,则需要将其转换为并保留它
  3. Return the list of keeped Employee 返回keeped Employee列表

1. Classic way with foreach-loop 1.具有foreach-loop经典方式

public static List<Employee> getEmployeeListFromPersonList(List<Person> list) {
    List<Employee> res = new ArrayList<>();
    for (Person p : list) {                 // 1.Iterate
        if (p instanceof Employee) {        // 2.Check type
            res.add((Employee) p);          // 3.Cast and keep it
        }
    }
    return res;
}

2. Java-8 way with Streams 2.使用Streams Java-8方式

public static List<Employee> getEmployeeListFromPersonList(List<Person> list) {
    return list.stream()                            // 1.Iterate
               .filter(Employee.class::isInstance)  // 2.Check type
               .map(Employee.class::cast)           // 3.Cast
               .collect(Collectors.toList());       // 3.Keep them
}

Do you mean something like: 你的意思是:

List<Employee> getEmployees(List<Person> personList){
    List<Employee> result = new ArrayList<Employee>();

    for(Person person : personList){
        if(person instanceof Employee) result.add((Employee)person);
    }

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM