1

I'm using Java, and wondering if it's possible to put methods directly into arrays as elements. Something like:

...[] arrayName = {herp(), derp(), jinkies()};

When I looked this up prior, some people mentioned "reflection," but I don't know what this is (I'm very new to programming). Is there a simple way to put methods into arrays (my goal is to spit them out randomly with a Random, and eventually terminate with a String parameter in each method named "quit" or something)? If not, how does reflection work for this circumstance (if at all)?

I am NOT only asking what reflection is. My exact (main) question is "Is it possible to put methods into arrays," and if it is, how is that done? What is the syntax for it?

Thank you for your time

Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
Ray25Lee
  • 65
  • 2
  • 8

2 Answers2

2

It is not possible in java to assign function as object.
But still you can use use lambda expression or similar structure for this. Which will not actually assign functions but you can use it like one.

Create a functional interface

@FunctionalInterface
interface MyFunction {
    public void fun();
}

Use lambda expressions to initialize array of that functional interfaces

MyFunction[] functions = new MyFunction[]{
    () -> System.out.println("I am herp"),
    () -> {
        int a = 2;
        int b = 3;
        System.out.println(a + b);
    }
};

Use the array like array of functions.

functions[0].fun();
afzalex
  • 8,254
  • 2
  • 29
  • 53
0

you can make a class for every method and make an array of classes. also for it to be easier do it with inner classes and it will be more readable.

(of course every class will share the same interface)

omry155
  • 11
  • 3
  • Why would it be easier with an "inner class" (I'm not sure what that is)? Also, would the syntax for a class array be "class[] arrayName" etcetera? – Ray25Lee Sep 30 '15 at 06:47