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.
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.
A generic class and a generic method can handle any type of data.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With