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!");
    }
}
5
  • 4
    Possible duplicate of Java - Creating an array of methods Commented Oct 29, 2018 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. Commented Oct 29, 2018 at 18:15
  • @KamilJarosz Since Java 8 you actually can. Commented Oct 30, 2018 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. Commented Oct 30, 2018 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. Commented Oct 30, 2018 at 18:57

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, I didn't know I could use this in Java, thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.