6

I am a Java newbie so my questions may look like an easy one. But I need some direction from your guys.

Here is my question: I have a class with bunch of methods, I would like to give these methods to user in a combox to select, based on their selection some code will run. Now I can do this by writing switch selection method. Where based on selection I use switch to run a particular method.

But my list of functions is pretty long close to 200, SO my questions to you is: is there a smarter way of doing this. Just point me to the right direction and I'll try to do the rest.

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
user1453817
  • 77
  • 2
  • 9

5 Answers5

8

You can use reflection, specifically: Class.getMethods() or Class.getDeclaredMethods().

Make sure you understand the differences between them (read the linked javadocs for this), if you don't - don't be afraid to ask.

amit
  • 175,853
  • 27
  • 231
  • 333
2

I think looking into Java Reflection would be the best place to start, assuming I've understood what you want to do correctly.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
2

you can use the Reflection for both listing the methods and calling them

http://docs.oracle.com/javase/tutorial/reflect/index.html

Using Java reflection to create eval() method

Community
  • 1
  • 1
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
1

You can use reflection (you can find a lot of information on Google) but it is not a good practice to simple show your methods to the user. In a more complex application you should try to separate presentation and true execution of what user want

Plínio Pantaleão
  • 1,229
  • 8
  • 13
0

Each selection could be represented by an Enum which is built as a set of function pointers:

public enum FunctionPointer {
F1 {
    public SomeObject doFunction(args) {
        YourClass.doMethod(args);
    }
},
//More enum values here...
}

The syntax will need a little work, but in the client you can just call

FunctionPointer.F1.doFunction("abc");
David
  • 1,887
  • 2
  • 13
  • 14
  • it really isn't that disimilar to your switch statement, but I dislike reflection for things that can be done without it. – David Jun 13 '12 at 15:09