首页 > 解决方案 > 动态参数重构

问题描述

我想使用 spring mvc 控制器来获取用户输入命令和参数,然后调用 sendCommand 方法。

调用url如:

http://127.0.0.1:8090/offheap/cmd?command=set a 1 b 2 c 3

控制器将接受以下命令作为字符串。

设置 a 1 b 2 c 3

然后它会调用 sendCommand 方法来设置 key a, value 1; 键 b,值 2;键 c,值 3 到本地缓存中。

控制器代码如下:

@ResponseBody
@RequestMapping(value = "/offheap/cmd")
public String userInput(@RequestParam String command) {

    String[] commandArray = command.split(" ");
    String cmd = StringUtils.upperCase(commandArray[0]);

    Object result;

    if (commandArray.length > 1) {
        //TODO, how to construct the args??
        byte[][] args = null;
        result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd), args);
    } else {
        result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd));
    }
    return JSON.toJSONString(result);
}

SendCommand 方法代码如下:

public Object sendCommand(OffheapCacheCommand command, byte[]... args) {
    //logic here, will ignore.
}

我知道 byte[]...args,应该构造一个 byte[][] 数组,其中包含要传递给 sendCommand 方法的数据。

但问题是 byte[][] 数组很难构造。

有人有好主意来构造这个 byte[][] 数组吗?

标签: javaparameters

解决方案


根据下面的代码解决了它。

 public String sendCommand(@RequestParam String command, @RequestParam String args) {

    String cmd = StringUtils.upperCase(command);
    String[] argsArray = args.split(" ");
    Object result;

    if (argsArray.length > 0) {
        byte[][] byteArray = new byte[argsArray.length][];
        for (int i = 0; i < argsArray.length; i++) {
            byte[] element = SerializationUtils.serialize(argsArray[i]);
            byteArray[i] = element;
        }

        result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd), byteArray);
    } else {
        result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd));
    }
    return JSON.toJSONString(result);
}

推荐阅读