【发布时间】:2025-11-26 02:25:01
【问题描述】:
根据我的用例,我有一个类 myClass 实现了一个接口 myInterface。
public class MyClass implementing MyInterface{
...
}
我有一个以 List 作为参数的方法。
myMethod(List<MyClass> listOfMyClass){
...
// want to make a call to third party API which has List<MyInterface>
thirdPartyAPI(listOfMyClass);
}
thirdPartyAPI(List<MyInterface> listOfMyInterface){
...
}
在上述情况下,我想在调用#thirdPartyAPI 时使用listOfMyClass。目前,我得到“方法 myMethod(List) 不适用于参数 thirdPartyAPI(List)。如果我需要更新我的设计或方法,请告诉我。任何帮助将不胜感激。谢谢。
经历过Java Generics -- Assigning a list of subclass to a list of superclass,但对我的情况没有帮助。
【问题讨论】:
-
您始终可以在您的网站上使用
List<MyInterface>并将此列表传递给第 3 方 API。如果这不是一个选项并且您无法更改 3rd 方 API(由于 PECS 确实应该更改),那么恐怕您必须创建一个新的List<MyInterface>并将所有条目从listOfMyClass复制到新列表.
标签: java list inheritance collections superclass