Java pass method reference as parameter to other method

前端 未结 5 1425
暗喜
暗喜 2021-02-04 07:53

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

5条回答
  •  一整个雨季
    2021-02-04 08:38

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

提交回复
热议问题