List of functions as a choice in Java

I'm new to Java, so my questions may seem easy. But I need some direction from your guys.

Here is my question: I have a class with many methods, I would like to give these methods to the user in combox for selection, based on their selection some code will be launched. Now I can do this by writing a switch selection method. Where based on the selection I use the switch to start a specific method.

But my list of functions is quite long, about 200, so my questions to you are: is there a more reasonable way to do this. Just lead me in the right direction and I will try to do the rest.

+6
source share
5 answers

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

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

+8
source

I think Java Reflection searches are the best place to start, assuming I understand that you want to do it right.

+2
source

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

+1
source

Each selection can be represented by Enum, which is created as a set of function pointers:

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

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

 FunctionPointer.F1.doFunction("abc"); 
0
source

Source: https://habr.com/ru/post/917977/


All Articles