Tag Archives: MVEL

[Solved] Mvel user-defined function error: duplicate function

The mvel custom expression repeats and reports an error: duplicate function

Reason: the function will be cached during the first call, and the function will be prompted to repeat when calling again

Scheme: put funciton into the cache first, and call the function in the declaration cache directly when calling again

The user-defined function name should not be the same as the parameter name

Example code:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MvelTest {
        
    @Test
    public void evalTest(){
        String roundup = "def roundup(num) { roundnum = null; if(num != null){ int roundnum = Math.round(num); } return roundnum; }";
        VariableResolverFactory functionFactory = new MapVariableResolverFactory();
        MVEL.eval(roundup, functionFactory);

        VariableResolverFactory resolverFactory = new MapVariableResolverFactory();
        resolverFactory.setNextFactory(functionFactory);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("A", new BigDecimal(2.33));
        map.put("B", new BigDecimal(4));
        String exp = "roundup(A*B)";
        System.out.println(MVEL.eval(exp, map, resolverFactory));

        System.out.println("------------");

        VariableResolverFactory resolverFactory2 = new MapVariableResolverFactory();
        resolverFactory2.setNextFactory(functionFactory);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("A", new BigDecimal(3.33));
        map2.put("B", new BigDecimal(2));
        System.out.println(MVEL.eval(exp, map2, resolverFactory2));
    }
}

Error code example

Add the roundup function to the cache

Successful first execution

Call again and add the roundup function to the cache again

A function in variableresolverfactory threw an exception