0

I have this string 1|1|1|1 and I want to sum the numbers inside spel statement. I tried this one but got wrong expression.

T(java.util.Arrays).stream(SERVICE_CLASS.split('|')).reduce(Integer::sum)

the log :

org.springframework.expression.spel.SpelParseException: Expression [new Object[] {T(java.util.Arrays).stream(SERVICE_CLASS.split('|')).reduce(Integer::sum)}] @81: EL1043E: Unexpected token. Expected 'rparen())' but was 'colon(:)'

the full code :

 @Test fun `test sum values`() {
    val cont = ScriptingContext.default();

    val contextrecord: Map<String, String> = mapOf(
        "value" to "1|1|1|1"
    )


    val context = cont.getEvalContext()
    context.setRootObject(contextrecord)
    val value = cont.parser.parseExpression("new Object[] {T(java.util.Arrays).stream(value.split('|')).reduce(Integer::sum)}").getValue(context) as Array<Object>
    println(value.toString())
    assertEquals(value[0], "4")
}

any suggest to do it ?

1 Answers1

1

SpEL stands for Spring Expression LANGUAGE. It is not Java; no lambdas, or method references are supported.

You can, however, register lambdas as SpEL functions; see Spring Expression Language - Java 8 forEach or stream on list

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • thanks for your answer, but the requirement said we need to do it without any additional methods. do you have any trick to do it ? – Anas Altarazi Jan 23 '23 at 14:16
  • No, there is no way to do that. The SpEL was designed mostly for simple properties access and it is significantly slow because it uses a reflection to call all those methods. What you trying to do (no additional methods) is an abuse of SpEL capabilities. Consider to use a scripting feature in Spring Integration instead: https://docs.spring.io/spring-integration/reference/html/scripting.html#scripting – Artem Bilan Jan 23 '23 at 14:39