gpt4 book ai didi

java - 类型转换泛型

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:02 24 4
gpt4 key购买 nike

我很难用谷歌搜索这个。我找了很多文章,但还是无法解决我的问题。

这是我的代码:

List<MyMainClass> mySource = (List<MyMainClass>) session.getAttribute("myAttribute");

session.getAttribute("myAttribute") 可能返回 List<MyObject1> List<MyObject2> 。两者 MyObject1 MyObject2 MyMainClass 的子类 现在我有 2 个功能。第一个接受 List<MyObject1> 另一个接受 List<MyObject2> 。现在我在 eclipse 中遇到错误

The method myMethod1(List<MyObject1>) in the type MyAction is not applicable for the arguments (List<MyMainClass>)

最佳答案

您无法在 session 属性中安全地存储具有相同删除 (List) 的不同泛型类型。所以:不要这样做。

相反,要么重构您的代码,以便无论该 session 属性的列表类型如何,它都是兼容的。这可能很难,但从长远来看,对我来说似乎不那么臭了。 IME,当您需要在单个变量中存储两个可能不同类型的内容时,通常会感觉设计很糟糕。

您可以交替使用两个不同的 session 属性,以便知道要转换为哪种更具体的列表类型。

List<MyObject1> mySource1 = (List<MyObject1>) session.getAttribute("myAttribute1");
if (mySource1 == null) {
List<MyObject2> mySource2 = (List<MyObject2>) session.getAttribute("myAttribute2");
if (mySource2 == null) {
// ???
} else {
// rock and roll
myMethod2(mySource2);
}
} else {
// proceed
myMethod1(mySource1);
}

如果您采用后一种方法,我建议您编写一个包装器对象或方法来为您管理这些详细信息。

关于java - 类型转换泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13132149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com