为什么我不能在Java中将对象转换为集合?

时间:2017-06-23 06:29:03

标签: java

我正在为一个班级编写单元测试,如下所示:

@Test
void testCreateStackResources()
{
    List<StackResource> stackResourceListExpected = new ArrayList<>();
    StackResource stackResource = new StackResource();
    stackResource.setLogicalResourceId("Sample-Logical-ID");
    stackResourceListExpected.add(stackResource);
    ListStackResourcesResult listStackResourcesResult = new ListStackResourcesResult();
    StackResourceSummary stackResourceSummary = new StackResourceSummary();
    stackResourceSummary.setLogicalResourceId("Sample-Logical-ID");
    listStackResourcesResult.setStackResourceSummaries((Collection<StackResourceSummary>) stackResourceSummary); // Problem in this line
    Mockito.when(amazonCloudFormation.listStackResources(Mockito.any(ListStackResourcesRequest.class))).thenReturn(listStackResourcesResult);
    List<StackResource> stackResourceListResult = cloudFormationManager.createStackResources(Mockito.anyString());
    Assert.assertEquals(stackResourceListExpected, stackResourceListResult);
}

现在,当我运行此代码时,它会给我一个错误,我无法将StackResourceSummary强制转换为Java中的Collection。

java.lang.ClassCastException: com.amazonaws.services.cloudformation.model.StackResourceSummary cannot be cast to java.util.Collection

另一方面,如果我之前创建一个数组列表,将StackResourceSummary的对象添加到列表然后运行UT,它会给我

objc[3648]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x10d19c4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10ea194e0). One of the two will be used. Which one is undefined.

这是非常奇怪的行为。我不知道为什么我不能把它投入集合?请帮忙。谢谢!

PS:有一个名为ListStackResourcesResult的单独类,它有一个如下的setter:

public void setStackResourceSummaries(java.util.Collection<StackResourceSummary> stackResourceSummaries) {
    if (stackResourceSummaries == null) {
        this.stackResourceSummaries = null;
        return;
    }

    this.stackResourceSummaries = new com.amazonaws.internal.SdkInternalList<StackResourceSummary>(stackResourceSummaries);
}

我正在尝试使用上述方法。

1 个答案:

答案 0 :(得分:1)

这是因为StackResourceSummary不会扩展或实现与集合相关的任何内容。

http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/cloudformation/model/StackResourceSummary.html

您需要创建一个集合并将StackResourceSummary实例添加到其中。例如:

List<StackResourceSummary> stackResourceSummaries = new ArrayList<StackResourceSummary>();
stackResourceSummaries.add(stackResourceSummary)

或者可能是这样

Arrays.asList(stackResourceSummary)

或使用像番石榴收藏品这样的第三方库。

然后你应该使用该集合作为参数。

listStackResourcesResult.setStackResourceSummaries(stackResourceSummaries); // Problem gone in this line