Call a function by its name specified in the java string

I would like to be able to call a function based on its name provided by the string. Sort of

public void callByName(String funcName){
   this.(funcName)();
}

I was looking a bit for lambda functions, but they are not supported. I thought about going to Reflection, but I'm a little new to programming, so I am not very good at this issue.

This whole question was raised in my OOP Java class when I started programming GUIs (Swing, swt) and events. I found that the use is object.addActionCommand()very ugly, because later I will need to make a Switch and catch the right command.

I would rather do something like object.attachFunction(btn1_click)so that it calls the function btn1_clickwhen the click is clicked.

+3
source share
6 answers

Java has methods, not functions. The difference is that methods have classes; you need to know the class to call the method. If this is an instance method, you need an instance to call it, but OTOH means you can easily view the method:

public void callByName(Object obj, String funcName) throws Exception {
    // Ignoring any possible result
    obj.getClass().getDeclaredMethod(funcName).invoke(obj);
}

Note that there are many potential exceptions to this, and things get more complicated if you want to pass arguments.

If you are talking about a class method, then you are doing a little different:

public void callClassByName(Class cls, String funcName) throws Exception {
    // Ignoring any possible result
    cls.getDeclaredMethod(funcName).invoke(null);
}

You can also explore with java.lang.reflect.Proxy.

+4
source

The following code will call the public method of the given name with no argument:

public void callByName(String funcName) {
    try {
        Method method = getClass().getDeclaredMethod(funcName);
        method.invoke(this, new Object[] {});
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
+2
source

Class.getDeclaredMethod(), , Method object:

Method method = MyClass.class.getDeclaredMethod("methodName", Event.class, String.class);
Object retVal = method.invoke(someEvent, someString);
+1

. .

+1

.forName(), .

, , , , , .

, . Sun Tutorial .

0

Yes, you can use the Reflection API for this, but I don’t think that this is a way to simply handle button events. Better ask how this can be done elegantly in the GUI that you use (Swing, SWT ..), I'm sure there should be an easier way than Reflection.

0
source

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


All Articles