Dynamic return type - Java Generics


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 ) {
          doanotherProcess(a.getxya(), a.getABC());
     return AnotherListOfType_ResultA;

Is it possible to write generic function for this?


If you want to generically map a List

Even if you want to write two functions like
public void doProcess(List


This video can help you solving your question :)
By: admin