gpt4 book ai didi

java - 在 java 中处理 List 而不进行类型转换

转载 作者:行者123 更新时间:2023-12-01 16:49:21 24 4
gpt4 key购买 nike

想象一下这个场景。

MyInterface{
method1();
method2();
...
}

MyImpl1 implements MyInterface{
...
}

MyImpl2 implements MyInterface{
...
}

SomeOtherClass{
...
public List<MyInterface> foo();
}


Service1{
public List<Impl1> service1Impl(){
SomeOtherClass obj = new SomeOtherClass(...);
return (List<Impl1>)obj.foo()
}
}

Service2{
public List<Impl2> service2Impl(){
SomeOtherClass obj = new SomeOtherClass(...);
return (List<Impl2>)obj.foo()
}
}

SomeOtherClass.java 的 foo() 可以返回 List<MyImpl1>List<MyImp2>基于在其构造函数中传递的参数。在 Service1 中,假设它返回 List<Impl1> ,对于 Service2 类,obj.foo() 将返回 List<Impl2> .

有没有办法避免显式类型转换?我正在考虑让 Service1 的 foo() 方法返回 List 而不是 List,而不在返回之前对其进行类型转换。

最佳答案

问题是 List<MyInterface>可能不包含相应子类的所有实例 Impl1Impl2 .

执行此操作的唯一(干净)方法是创建 SomeOtherClass通用:

class SomeOtherClass<T extends MyInterface>{
public List<T> foo();
}

然后:

class Service1 {
public List<Impl1> service1Impl(){
SomeOtherClass<Impl1> obj = new SomeOtherClass<>(...);
return obj.foo();
}
}

class Service2 {
public List<Impl2> service2Impl(){
SomeOtherClass<Impl2> obj = new SomeOtherClass<>(...);
return obj.foo();
}
}

关于java - 在 java 中处理 List<Interface> 而不进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668611/

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