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.

5 Answers 5

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.

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

Comments

2

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

Comments

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

Comments

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

Comments

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");

1 Comment

it really isn't that disimilar to your switch statement, but I dislike reflection for things that can be done without it.

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.