Good day! The other day I was puzzled with the question: how can I make a method call through another variable? That is, for example, the user enters a string with the name of the method, and I have to call it. Saw (seemingly) something like this in JavaScript when assigning a variable to a function. Please help, thanks in advance.

  • 3
    In java it will be a serious code smell, but perhaps through reflection - etki
  • one
    In this case (if the number of methods is not very large) it is better to create an enum, for each element of which a call is associated with. method. First, you try to get the enum element through the valueOf () method, thereby checking the correctness of the input, and then you execute the corresponding. method. You should not use reflection without real need - I. Perevoz

1 answer 1

This can be done using Reflection - http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html

For example, for a class with the name "my class", we will find the method "my method" with parameterTypes parameterTypes . And then call it for the objectToInvokeOn object with params parameters:

 // Находим класс Class<?> c = Class.forName("class name"); // Находим метод Method method = c.getDeclaredMethod ("method name", parameterTypes) // Вызываем метод для объекта method.invoke (objectToInvokeOn, params) 

It is possible and easy to find a method for a known object:

 Method method = myObject.getClass().getMethod("method name", parameterTypes); method.invoke(myObject, params);