Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Generic Type for same functionality

I am having a scenario where two functions are identically similar but the Class object used in the two differ, similar like this,

public int function1(inputObject input){
    LeadMaster lead= input.getLeadMaster();
    PropertyUtils.setProperty(lead, input.getKey(), input.getValue());
    return 0;
}

And similarly other function like,

public int function2(inputObject input){
    DealMaster deal= input.getDealMaster();
    PropertyUtils.setProperty(deal, input.getKey(), input.getValue());
    return 0;
}

How can I use the generic class for the master object in above object? I haven't used generics yet.

like image 487
AJN Avatar asked Nov 01 '17 12:11

AJN


People also ask

What is a generic method and when should it be used?

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.

Can generic class handle any type of data?

A generic class and a generic method can handle any type of data.


1 Answers

If you wish your method to work with any property of the inputObject class, you can pass a functional interface that returns the required property of a given inputObject instance:

public <T> int function(inputObject input, Function<inputObject,T> func) {
    T obj = func.apply(input);
    PropertyUtils.setProperty(obj, input.getKey(), input.getValue());
    return 0;
}

Now you can call this method with

function(input,inputObject::getLeadMaster);

or

function(input,inputObject::getDealMaster);
like image 167
Eran Avatar answered Oct 20 '22 12:10

Eran