Is it possible to create an array of functions in Java? Or is this not possible?

Recommended Answers

All 4 Replies

Not possible using "ordinary" Java, but possible using the "reflection" classes - have a look at the class java.lang.reflect.Method to get a quick flavour of what its all about. I can give you a lot more info on reflection if this looks like a direction you wan to go in.

That looks about right to me... how do I use it?

OK. Start with this quick tutorial:
http://download.oracle.com/javase/tutorial/reflect/

In summary you get the Class of each classes containing your methods (Java refers to "functions" as "methods"), then from the Class get the Method objects representing the methods themselves. You can store those in an array of Methods. You can use "invoke" to invoke any of those methods with whatever parameters they need. It's a bit of a slog the very first time you do it, but once you get the first one sorted it's easy, and the code can be very compact.

(I tried to answer the question exactly as you asked it but depending on what your underlying requirement is, that may not have been the right question. For example, if you just want to call one of n methods based on an integer index 1..n it may be simpler just to have a switch with the method calls hard-coded for each case.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.