I would like to do something like below.
private <T> void sliceGenericData (List<T> peData, **FunctionType** getterFunctionX) { // ... Some Code ... <T>.getterFunction() // ... Some Code ... }
A and B class will be my generic type as <T>. Example for a getter function for class A and B.
public class A{ long x = 5; public long getterFunction1(){ return x; } } public class B{ long x = 1; public long getterFunction2(){ return x; } }
I want to pass a getterFunction as argument to my sliceGenericData()
and I would like to use it on type <T> (Class A or B). Since those classes have different name of getter functions as getterFunction2, getterFunction1
. How can I do it?
Advertisement
Answer
You can pass a function taking the type as param and producing a Long like this:
private <T> void sliceGenericData (List<T> peData, Function<T, Long> fn) { ... // apply your Object Long res = fn.apply(myObj); ... }
Invoke the method by providing the appropriate method for the type:
sliceGenericData(myList, A::getterFunction1);