Reputation: 87
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.
Upvotes: 6
Views: 207
Reputation: 1927
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");
Upvotes: 0
Reputation: 1239
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
Upvotes: 1
Reputation: 26737
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
Upvotes: 2
Reputation: 38345
I think looking into Java Reflection would be the best place to start, assuming I've understood what you want to do correctly.
Upvotes: 2
Reputation: 178451
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.
Upvotes: 8