4

Is there a way to get MVEL 2.0 ( http://mvel.codehaus.org/ ) to work with functions with optional parameters?

I would like to be able to eval this:

trunc('blahblah',2)

but also

trunc('blahblah',2,'[...]');

Now i have tried:

def trunc(param1,param2,param3) { ... impl ... }

That gives an exception if i try to call it with only 3 parameters. I also tried:

def trunc(param1,param2,param3) { ... impl ... } def trunc(param1,param2) { ... impl ... }

But the second one seems to completely overwrite the first definition.

Thanks

JP-Ulm
  • 161
  • 1
  • 2
  • 6

2 Answers2

1

In java you can declare multiple methods with the same name, but a different arguments. That way you can support (in a limited way) optional parameters. Eg.:

private void method(Object obj1) {
    Object obj2 = new Object("Default");
    method(obj1, obj2);
}

private void method(Object obj1, Object obj2) {
    doStuff(...);
}

Calling method() is possible with one or two arguments :)

Kr1z
  • 349
  • 3
  • 6
0

MVEL has a bug where it accepts methods with varargs, but only executes the method with non-varargs. So you should have both a varargs and non-varargs method. Do a lookup on the varargs method, but only the non-varargs will get called.

parserContext = new ParserContext();
parserContext.addImport("color", MyImplementation.class.getMethod("color", double[].class));

In your implementation class:

// This one is used for lookup, but never called.
public static Color color(double... values) {} 

public static Color color(double gray) {}
public static Color color(double red, double green, double blue) {}

If you want to do this with arbitrary object types, use Object[].class. Keep in mind that you lose type safety by doing this.

Frederik
  • 12,867
  • 9
  • 42
  • 52