审查生成的命令调度器

来自 反射
Java 25 LTS 高级 6分钟 找出 5处问题

在这段生成的调度器接收应用命令前进行审查。

调度一组小型允许列表中的单参数命令,支持声明为基本类型或接口的形参,保留有用失败,并安全复用已验证计划与服务实例。

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; }
    }
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误