Call a known function (with parameters) in a class whose name is determined by a string variable

I have a group of classes with different names, each of which has a performLogic function that takes several predefined parameters (always the same):

public final class DoSomeAction extends SetupAction {
    public void performLogic(param1, param2...

I need a way that I can call it this way:

String actionName = "DoSomeAction";
actionName.performLogic(param1, param2...);

Hope this is clear what I'm trying to do.

Thanks for the tip and pointing me to class.forName (). After some further research, I was able to implement the following:

try {
    Class actionClass = Class.forName(blockAction);

    Object obj = actionClass.newInstance();

    Class[] parameterTypes = new Class[2];
    parameterTypes[0] = String.class;
    parameterTypes[1] =  String.class;

    Method performLogic = actionClass.getDeclaredMethod("performLogic", parameterTypes);

    performLogic.invoke(obj, param1, param2);
}
catch(ClassNotFoundException e) {
    cat.error("Class not found: " + e.toString());
}
+4
source share
1 answer

You can use reflection

Object action = ???; // perhaps you need .newInstance() for action class
                     // Hopefully you have a interface with performLogic

String methodName = "performLogic";
try {
    Method method = action.getClass().getMethod(methodName, param1.class, param2.class);
    method.invoke(action, param1, param2);
} catch (SecurityException | NoSuchMethodException e) {
    // Error by get Method
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {        
    // Error by call Method
}
+2
source

All Articles