首页 > 解决方案 > Java:将字符串参数解析为数组

问题描述

我有一个接受字符串作为参数的方法。现在,我需要将字符串参数转换为 java 数组作为参数。

这是Java代码:

private static Class<?> convertToType(String par1) throws Exception {
    var string = par1.trim();
    //System.out.println("the string is: " + par1);
    try {
        Integer.parseInt(string);
        return int.class;
    } catch (NumberFormatException e) {
    }

    try {
        Double.parseDouble(string);
        return double.class;
    } catch (NumberFormatException e) {
    }

    try {
        if (string.toLowerCase().equals("true") || string.toLowerCase().equals("false")) {
            Boolean.parseBoolean(string);
            return boolean.class;
        }
    } catch (NumberFormatException e) {
    }

    try {
        if (string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"') {
            return String.class;
        }
    } catch (Exception e) {
    }

    try {
        return parseToEnum(string).getClass();
    } catch (Exception e) {
    }
    throw new Exception();
}

这是该方法调用的示例方法:

getA(1,2,3, {4,5,6});

在这种情况下, 中的值{4,5,6}表示数组。而 1,2,3 代表整数。

当我调用 getA 方法时,程序将调用 convertToType 方法将参数转换为相应的数据类型。目前,我已经能够将字符串解析为 int、double、boolean 和 enum。但我不确定如何将其解析为数组对象。

我当前的代码执行它在 convertToType 方法中得到 java.lang.exception。

标签: javaarrays

解决方案


推荐阅读