How to represent a list of values in Janino script

592 Views Asked by At

I'm using Janino to evaluate a script and I don't know how to represent a list of values in the script

<!-- https://mvnrepository.com/artifact/org.codehaus.janino/janino -->
        <dependency>
            <groupId>org.codehaus.janino</groupId>
            <artifactId>janino</artifactId>
            <version>3.1.0</version>
        </dependency>

I need to evaluate containsAll script, for example: attributeA.containsAll([3,5])

I've tried using [] and Arrays.asList but the compiler either says: "org.codehaus.commons.compiler.CompileException: Line 1, Column 25: Unexpected token "[" in primary" or it says: org.codehaus.commons.compiler.CompileException: Line 1, Column 32: Unknown variable or type "Arrays"


import com.my.project.MyCollection;
import org.codehaus.commons.compiler.CompileException;
import org.codehaus.janino.ExpressionEvaluator;

private static void evalExpression(Map<String, MyCollection> fields)
{
    String script= "attributeA.containsAll([3,5])";

    try {
        ExpressionEvaluator ee = new ExpressionEvaluator();

        Class[] parameterTypes = new Class[fields.size()];
        String[] parameterNames = new String[fields.size()];
        Object[] arguments = new Object[fields.size()];
        int i = 0;
        for (Map.Entry<String, MyCollection> field : fields.entrySet()) {
            String fieldName = field.getKey();
            MyCollection fieldValues = field.getValue();

            parameterNames[i] = fieldName;
            parameterTypes[i] = MyCollection.class;
            arguments[i]=fieldValues;

            i++;
        }

        ee.setParameters(parameterNames, parameterTypes);

        ee.setExpressionType(Boolean.class);

        // And now we "cook" (scan, parse, compile and load) the fabulous expression.
        ee.cook(script);

        // Eventually we evaluate the expression - and that goes super-fast.

        Boolean result = (Boolean) ee.evaluate(arguments);
        System.out.println(result);

    }
    catch (Exception ex){
        System.out.println(ex.getMessage());
    }
}

I expect the output of false/ true, but instead an org.codehaus.commons.compiler.CompileException is thrown

1

There are 1 best solutions below

0
morenaPG On

I added to the script : "import static java.util.Arrays.asList; "

and used the syntax: attributeA.containsAll(asList(3,5))