有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java动态参数重构

我想使用spring mvc控制器获取用户输入命令&;然后调用sendCommand方法

调用url,比如:

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

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

set a 1 b 2 c 3

然后它将调用sendCommand方法来设置键a,值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.
}

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

但问题是字节[][]数组很难构造

有谁有好主意来构造这个字节[]数组吗


共 (1) 个答案

  1. # 1 楼答案

    根据下面的代码解决了它

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