Java pass method reference as parameter to other method

前端 未结 5 1433
暗喜
暗喜 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

    Your getX() methods can be seen as a Function that accepts a DataStore instance and returns a float.

    In Java 8 you can represent them with method references :

        float[] aArray = getValuesAsArray(dataMap, DataStore::getA);
        float[] bArray = getValuesAsArray(dataMap, DataStore::getB);
        float[] cArray = getValuesAsArray(dataMap, DataStore::getC);
    

    Then your getValuesAsArray will accept a Function parameter and execute the function :

    private static float[] getValuesAsArray(Map dataMap, Function func) {
        int i = 0;
        int nMap = dataMap.size();
        float[] fArray = new float[nMap];
        for (Map.Entry entry : dataMap.entrySet()) {
            DataStore ds = entry.getValue();
            fArray[i] = func.apply(ds);
            i++;
        }
        return fArray;
    }
    

    Without using Java 8, you can define your own interface that contains a method that accepts a DataStore instance and returns a float. Then, instead of using Java 8 method references, you would have to pass to your getValuesAsArray method an implementation of that interface (you could use an anonymous class instance implementing the interface) which calls one of the getX() methods.

    For example :

    public interface ValueGetter
    {
        public float get (DataStore source);
    }
    
    float[] aArray = getValuesAsArray(dataMap, new ValueGetter() {public float get (DataStore source) {return source.getA();}});
    float[] bArray = getValuesAsArray(dataMap, new ValueGetter() {public float get (DataStore source) {return source.getB();}});
    float[] cArray = getValuesAsArray(dataMap, new ValueGetter() {public float get (DataStore source) {return source.getC();}});
    

    And

    private static float[] getValuesAsArray(Map dataMap, ValueGetter func) {
        int i = 0;
        int nMap = dataMap.size();
        float[] fArray = new float[nMap];
        for (Map.Entry entry : dataMap.entrySet()) {
            DataStore ds = entry.getValue();
            fArray[i] = func.get(ds);
            i++;
        }
        return fArray;
    }
    

提交回复
热议问题