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

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"){
        } else if (method == "col"){

And so on. Please let me know!


Take a look at the reflection API:



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)

Then you can call it with something like

printCells(cells, cell::getSubrow)


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


when no getters are available you could also use: printCells(cells, c -> c.col)
This does not seem to work for me. When I paste your solution into my code, it tells me that “the class Function does not exist”. I don’t know why this doesn’t work… Lino’s solution for calling the function throws about 11 different errors
– Kaspar Poland
54 mins ago
Oh, which version of Java are you using? I was assuming 8..
Everything works! I was using Processing 3.3.3, in which I looked up the documentation for lambdas, and they do not support lambdas. I transported everything to eclipse, and everything works as intended! Thanks dude! You are the best!!!!
– Kaspar Poland
5 mins ago


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) {

And it could be called that way:

printCells(cellArr, "getContent");

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