Review a generated command dispatcher

from Reflection
Java 25 LTS advanced 6 min 5 issues to find

Review this generated dispatcher before it accepts application commands.

Dispatch a small allowlisted set of one-argument commands, support declared primitive or interface parameters, preserve useful failures, and reuse validated plans and service instances safely.

Java
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class GeneratedDispatcher {
    private static final Map<String, Method> CACHE = new HashMap<>();

    static Object dispatch(String className, String methodName,
            Object argument) throws Exception {
        Class<?> type = Class.forName(className);
        Object target = type.getDeclaredConstructor().newInstance();
        String key = className + "#" + methodName;
        Method method = CACHE.computeIfAbsent(key, unused -> {
            try {
                return type.getDeclaredMethod(methodName, argument.getClass());
            } catch (ReflectiveOperationException error) {
                throw new RuntimeException(error);
            }
        });
        method.setAccessible(true);
        try { return method.invoke(target, argument); }
        catch (Exception error) { return null; }
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error