Search code examples
javagenericsjava-8generic-method

Generic Method That takes unique parameter and returns unique parameters Java


I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.

ie.

public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}

public returnOject2 myfunction( paramObject2 a, int a){
 returnObject2 = new returnObject2();
 returnObject2.a = paramObject2.a;
 return returnObject2;
}

As you can see above, both the function do the same task but they take different parameters as input and return different objects.

I would like to minimize writing different functions that does the same task.

Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?

paramObject and returnObject are basically two classes that have different variables. They are not related to each other.

My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.

my aim is to do something like this (if possible):

public static < E > myfunction( T a, int a ) {
  // do work
}

The return type E and the input T can keep varying.


Solution

  • Make interface Foo and implement this interface in both paramObject1 and paramObject2 class. Now your method should be look like:

    public Foo myFunction(Foo foo, int a){
        //Rest of the code.
        return foo;
    }