How do you cast a List of supertypes to a List of subtypes?

前端 未结 17 1541
面向向阳花
面向向阳花 2020-11-22 08:43

For example, lets say you have two classes:

public class TestA {}
public class TestB extends TestA{}

I have a method that returns a L

17条回答
  •  深忆病人
    2020-11-22 09:01

    class MyClass {
      String field;
    
      MyClass(String field) {
        this.field = field;
      }
    }
    
    @Test
    public void testTypeCast() {
      List objectList = Arrays.asList(new MyClass("1"), new MyClass("2"));
    
      Class clazz = MyClass.class;
      List myClassList = objectList.stream()
          .map(clazz::cast)
          .collect(Collectors.toList());
    
      assertEquals(objectList.size(), myClassList.size());
      assertEquals(objectList, myClassList);
    }
    
    
    

    This test shows how to cast List to List. But you need to take an attention to that objectList must contain instances of the same type as MyClass. And this example can be considered when List is used. For this purpose get field Class clazz in constructor and use it instead of MyClass.class.

    提交回复
    热议问题