0

I have a two similar objects (actually entities). From a function, I get either one of them. So I know which one I got only during the runtime.

I need to do processing on the object I got. Both have same set of processes to be applied. So I would like to write Generic function both both these classes. I tried to write, but I did not get clear idea how to implement this.

 List<MyClassA> objAList;
 List<MyClassB> objBList:
 List<ResultA> resultObjAList;
 List<ResultB> resultObjBList;

 objAList = getResult();
 objBList = getResult()

 if ( objAList != null ) {
     // Set of function calls on ObjA to process further. For ex:
    resultObjAList =   doProcess(objAList);

 } else {
     // Same set of function class to process. For Ex:
     resultObjBList = doProcess(objBList);
 }

I am about to decide to write two different functions that look similar to do the processing for each of these classes, after a few attempts.

Note the doProcess function above. It takes the objA or objB and return resultObjA or resultObjB.

I cannot wrap both of these with an interface. So option is ruled out.

doProcess looks like this:

  List<ResultA> doProcess( List<MyClassA> A ) {
     for ( MyClassList a : A ) {
          a.getSomething();
          doanotherProcess(a.getxya(), a.getABC());
          ....
     }
     return AnotherListOfType_ResultA;
  }

Is it possible to write generic function for this?

4

2 回答 2

1

如果您想将输入一般地映射List<MyClassA>ResultAList<MyClassB>输入到ResultB,那么我可以回答这是不可能的:没有办法用 Java 泛型来表达结果类型对输入类型的那种依赖性。

从理论上讲,您可以使用 , 参数化MyClassAResultAMyClassA<ResultA>它可能只会让您的代码变得一团糟。

于 2013-08-03T15:57:26.877 回答
1

即使您想编写两个类似的函数
public void doProcess(List<ObjectA> list); 也是 public void doProcess(List<ObjectB> list); 不可能的,因为泛型只是编译时构造,因此两个函数具有相同的擦除。

您能做的最好的事情就是拥有一个函数并根据某些条件转换您的对象。

于 2013-08-03T16:09:44.663 回答