Kaspar Poland
Kaspar Poland

Reputation: 105

Using params to call methods

This is a question about programming in general. I want to be able to put a param into a function and have an object call that param, for example:

    void printCells(cell[] cellArr, String method) {
       for (int i = 0; i < cellArr.length; i++) {
          cell c = cellArr[i];
          println(c.method);
       }
    }

This code is just a utility function for my ease of use, and I want to be able to print off some value within the cell object, which has values of value, row, col, subrow, and subcol. I want to use this function like:

    printCells(cells, subrow);

And it will go through the above for loop and print off the subrow value from every cell object in the cells array, which I pass in as cellArr.

Is this even possible? Or do I need a long if statement such as:

    void printCells(cell[] cellArr, String method) {
      for (int i = 0; i < cellArr.length; i++) {
        cell c = cellArr[i];
        if (method == "row"){
          println(c.row);
        } else if (method == "col"){
          println(c.col);
      }
    }

And so on. Please let me know!

Upvotes: 0

Views: 92

Answers (2)

C.Champagne
C.Champagne

Reputation: 5489

I think that using lambdas or method references as in xs0's answer is preferable but if the method you need to call can only be referenced by its name or if you can only use an older version of Java( < 8) then it is worth using reflection.

void printCells(cell[] cellArr, String getter) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Method getterMethod = cell.class.getMethod(getter);
    for (cell c : cellArr) {
        println(getterMethod.invoke(c));
    }
}

And it could be called that way:

printCells(cellArr, "getContent");

(Note that you have to take the thrown exceptions in account.)

Upvotes: 1

xs0
xs0

Reputation: 2897

You can do it using reflection, but it's possibly easier to use lambdas:

void printCells(cell[] cellArr, Function<cell, Object> getter) {
    for (cell c : cellArr)
        println(getter.apply(c));
}

Then you can call it with something like

printCells(cells, cell::getSubrow)

or

printCells(cells, cell -> cell.subrow) // thanks to Lino for suggestion

Upvotes: 2

Related Questions