I am trying to pass a selected \"get\"-method of class A to a method in class B. I have checked out Java Pass Method as Parameter, but I was not able to adopt the interface appr
Awhile ago I used java.util.concurrent.Callable but it doesn't seem to work out, thanks to @Eran.
Instead, you can use Java 8's java.util.function.Function
, like so (without the lambdas):
public static void main(String[] args) {
//...
getValuesAsArray(dataMap, new Function(){ public Float apply(DataStore input) { return input.getA(); }});
getValuesAsArray(dataMap, new Function(){ public Float apply(DataStore input) { return input.getB(); }});
getValuesAsArray(dataMap, new Function(){ public Float apply(DataStore input) { return input.getC(); }});
}
private static float[] getValuesAsArray(Map dataMap, Function function) {
int i = 0;
int nMap = dataMap.size();
float[] fArray = new float[nMap];
for (Map.Entry entry : dataMap.entrySet()) {
DataStore ds = entry.getValue();
fArray[i] = function.apply(ds);
i++;
}
return fArray;
}