gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:08:20 25 4
gpt4 key购买 nike

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

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

最佳答案

如果您知道您传递的表达式应该被评估为什么类型,您可以使用泛型。我还会要求参数中使用字符串而不是对象。因为 SpEL 始终是一个字符串。

private static <T> T calculateExperssion(String expr, Class<T> class) {
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression(expr);
return class.cast(expression.getValue());
}

使用此选项时,第二个参数将为 String.classInteger.class

关于java - 使用返回不同类型的 SpelExpressionParser 解析表达式的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47051306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com