简体   繁体   English

如何在Java中将对象从超类转换为子类?

[英]How to get the objects from superclass to subclass in java?

A class Person has several subclasses including Employee . Person具有几个子类,包括Employee

There is a method which is supposed to return another List which consists of just the Employee objects from the original list of Person . 有一种方法应该返回另一个List ,该List仅包含Person原始列表中的Employee对象。

How do I accomplish this in Java? 如何在Java中完成此操作?

Simple example for you: 为您提供的简单示例:

public class Test {
public static void main(String[] args) {
    List<Person> lst = new ArrayList<Person>() {
        {
            add(new Person());
            add(new Person());
            add(new Employee());
            add(new Employee());
            add(new AnotherPerson());
            add(new AnotherPerson());
        }
    };

    List<Person> employes = lst.stream().filter(item -> item instanceof Employee).collect(Collectors.toList());
    System.out.println(employes.size());
}

class Person {

}

class Employee extends Person {

}

class AnotherPerson extends Person {

}
}

Since 以来

Person has several subclasses 人有几个子类

and

return another List which consists of just the Employee objects 返回另一个仅由Employee对象组成的List

You shall use instanceOf to accomplish looking for specifically looking for Employee class from a List<Person> . 您将使用instanceOf来完成从List<Person>专门查找Employee类的查找。 Just for eg: 仅用于例如:

List<Person> personList // assigned to something
List<Employee> employeeList = new ArrayList<>();
for(Person person : personList)  {
    if(person !=null && person instanceOf Employee) { 
        employeeList.add((Employee) person);
    }
}

The sample from java-nutsandbolts might help you. java-nutsandbolts中的示例可能会为您提供帮助。

When using the instanceof operator, keep in mind that null is not an instance of anything. 使用instanceof运算符时,请记住, null不是任何实例。

Other answers and comments should provide a solution, but if you want a generic solution, then you could do something like this: 其他答案和评论应该提供解决方案,但是如果您需要通用解决方案,则可以执行以下操作:

public static <T extends Person> List<T> getPersonTypes(Class<T> cls, Collection<Person> c)
{
  return c.stream()
      .filter(Objects::nonNull)
      .filter(p -> cls.isAssignableFrom(p.getClass()))
      .map(cls::cast)
      .collect(Collectors.toList());
}

And then call something like this: 然后调用这样的内容:

List<Employee> employees = getPersonTypes(Employee.class, listOfPersons);

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

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