例如,假设你有两个类:

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

我有一个返回List<TestB>的方法,我想将该列表中的所有对象强制转换为TestB,以便最终得到List<TestB>。


当前回答

在Java 8中,实际上可以做到

List<TestB> variable = collectionOfListA
    .stream()
    .map(e -> (TestB) e)
    .collect(Collectors.toList());

其他回答

我必须用公司系统的方法来实现:

interface MyInterface{}
Class MyClass implements MyInterface{}

该方法接收一个接口列表,也就是说,我已经实例化了一个接口列表

private get(List<MyInterface> interface) {
   List<MyClass> myClasses = interface.stream()
                 .filter(MyClass.class::isInstance)
                 .map(MyClass.class::cast)
                 .collect(Collectors.toList());
}

不过我认为你选错方向了……如果该方法返回一个TestA对象列表,那么将它们强制转换到TestB确实是不安全的。

基本上,您是在要求编译器允许您在不支持TestA类型的TestB上执行操作。

当您强制转换对象引用时,您只是强制转换引用的类型,而不是对象的类型。强制转换不会改变对象的实际类型。

Java没有转换对象类型的隐式规则。(与原语)

相反,您需要提供如何将一种类型转换为另一种类型并手动调用它。

public class TestA {}
public class TestB extends TestA{ 
    TestB(TestA testA) {
        // build a TestB from a TestA
    }
}

List<TestA> result = .... 
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
   data.add(new TestB(testA));
}

这比在有直接支持的语言中更冗长,但它是可行的,您不需要经常这样做。

正如Steve Kuo提到的,您不能将List<TestB>转换为List<TestA>,但是您可以将List<TestA>的内容转储到List<TestB>。试试下面的方法:

List<TestA> result = new List<TestA>();
List<TestB> data = new List<TestB>();
result.addAll(data);

我没有尝试过这段代码,所以可能有错误,但其思想是,它应该遍历数据对象,将元素(TestB对象)添加到List中。我希望这对你有用。

由于这是一个被广泛引用的问题,目前的答案主要解释了为什么它不起作用(或者提出了我永远不希望在生产代码中看到的俗套、危险的解决方案),我认为应该添加另一个答案,展示陷阱和可能的解决方案。


在其他回答中已经指出了一般情况下这不能工作的原因:转换是否实际有效取决于原始列表中包含的对象的类型。当列表中有对象的类型不是TestB类型,而是TestA的不同子类时,则强制转换无效。


当然,类型转换可能是有效的。有时,您拥有编译器无法使用的类型信息。在这些情况下,可以强制转换列表,但通常不建议这样做:

一个人可以……

... 转换整个列表或 ... 强制转换列表中的所有元素

The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.

调试这些虚假classcastexception的问题可以通过Collections#checkedCollection系列方法缓解。


基于类型筛选列表

从List<Supertype>转换到List<Subtype>的一种更类型安全的方法是实际筛选列表,并创建一个只包含具有特定类型的元素的新列表。这种方法的实现有一定程度的自由度(例如,关于空项的处理),但一种可能的实现可能是这样的:

/**
 * Filter the given list, and create a new list that only contains
 * the elements that are (subtypes) of the class c
 * 
 * @param listA The input list
 * @param c The class to filter for
 * @return The filtered list
 */
private static <T> List<T> filter(List<?> listA, Class<T> c)
{
    List<T> listB = new ArrayList<T>();
    for (Object a : listA)
    {
        if (c.isInstance(a))
        {
            listB.add(c.cast(a));
        }
    }
    return listB;
}

这个方法可以用来过滤任意列表(不仅仅是关于类型参数的给定子类型-超类型关系),如下例所示:

// A list of type "List<Number>" that actually 
// contains Integer, Double and Float values
List<Number> mixedNumbers = 
    new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));

// Filter the list, and create a list that contains
// only the Integer values:
List<Integer> integers = filter(mixedNumbers, Integer.class);

System.out.println(integers); // Prints [12, 78]