0

I have a big problem that I really don't know the solution to, I can't seem to figure it out after hours of looking and trying stuff around...

I want to have an array which has methods inside, and I want to call them later on with their respective index, the test code looks like this:

package methods;

public class Methods {
    public static void main(String[] args) {
        Methods[] methodsArray = {print_something(), something_else()};
        methodsArray[0];
    }

    public static void print_something() {
        System.out.println("Hiya!");
    }
    public static void something_else() {
        System.out.println("Something else!");
    }
}
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
ree
  • 31
  • 4
    Possible duplicate of [Java - Creating an array of methods](https://stackoverflow.com/questions/4280727/java-creating-an-array-of-methods) – takendarkk Oct 29 '18 at 18:14
  • 1
    You can't readily do this in Java. Functions are not first-class objects. You need to rewrite your code to use functors or function interfaces. – Kamil Jarosz Oct 29 '18 at 18:15
  • @KamilJarosz Since Java 8 you actually can. – Mark Rotteveel Oct 30 '18 at 17:08
  • @MarkRotteveel, You can.... kind of. But I thought you still have to structure your code appropriately. Can you actually do this without resorting to an interface in Java 8? That's the only way I know how to do it: an interface with a single function and a lambda expression. – Kamil Jarosz Oct 30 '18 at 17:25
  • 1
    @KamilJarosz Yes you need an interface (but those already exist, eg `Runnable`), but you don't necessarily need a lambda expression: a method reference works as well. – Mark Rotteveel Oct 30 '18 at 18:57

1 Answers1

6

You can do

public class Methods {
    public static void main(String[] args) {
        Runnable[] methodsArray = {Methods::print_something, Methods::something_else};
        methodsArray[0].run();
    }

    public static void print_something() {
        System.out.println("Hiya!");
    }
    public static void something_else() {
        System.out.println("Something else!");
    }
}

Accessing an array, only ever accesses the array and you can't change it to call a function in Java. You can do this in Kotlin, Groovy and Scala with operator overloading on a custom class (but not an array)

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106