有 Java 编程相关的问题?

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

使用返回不同类型的SpelExpressionParser解析表达式的java方法

我创建了一个方法来计算一个表达式,它可以是字符串连接,也可以是算术运算。所以我想创建一个可以返回字符串或整数的方法。有没有更优雅、更正确的方法

private static Object calculateExpression(Object object) {
        ExpressionParser expressionParser = new SpelExpressionParser();
        Expression expression = expressionParser.parseExpression((String) object);

        if (expression.getValue() instanceof Integer) {
            return expression.getValue();
        } else if (expression.getValue() instanceof String) {
            return expression.getValue();
        }
        throw new IllegalArgumentException("Can process only Strings or Integers");
    }

共 (0) 个答案