我有一堂这样的课
class Dummy{
public getData(Info info){
List<SomeType> list = info.getDataAsPerInfo();
List<SomeType> result=new List<>();
for(SomeType someType: list){
// extracting data from someType, lets say this data is
// resType (it also of SomeType)
result.add(resType);
}
}
public static void main(String args[]){
Info1 info = new Info1(); // Info1 extends Info
// adding paramters to info
new Dummy().getData(info);
}
}
现在的问题是我有几个 Info 类,例如 Info1、Info2 ...
getData 方法可能返回不同类型的列表。我不知道如何在不重写每个 Info 类的代码的情况下实现这一目标(这将涉及用该类的 getdataAsPerInfo 函数的返回类型替换 SomeType
)。
有没有一种方法可以让我根据传递给 getData 函数的 Info 类型以某种方式使用 SomeType
?在这种情况下最好的方法是什么?谢谢 !!
最佳答案
只需查看 Generics 的 Oracle 教程即可。 .
您不仅可以将一个特定类定义为列表元素的类型,还可以将一系列类或实现特定接口(interface)的类定义为类型。
编辑以纳入评论。
当您的 Info.getDataAsPerInfo()
根据使用的 InfoX 类返回不同对象的列表时,这将是通用接口(interface)的用例。
public interface Info<T> {
List<T> getDataAsPerInfo();
}
实现如下:
public class Info1 implements Info<SomeType>
或
public class Info2 implements Info<SomeOtherType>
然后你的Dummy
类看起来像
class Dummy {
public getData(Info<T> info) {
List<T> list = info.getDataAsPerInfo();
List<T> result=new List<>();
for(T someType: list){
// extracting data from someType, lets say this data is
// resType (it also of SomeType)
result.add(resType);
}
}
public static void main(String args[]){
Info1 info = new Info1(); // Info1 extends Info<SomeType>
// adding paramters to info
new Dummy().getData(info);
}
}
关于Java:如何让列表类型接受变量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38873376/