Using Generic Type for same functionality

AJN :

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.

Eran :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=445200&siteId=1