Print
MVEL Type Conversion

MVEL is a dynamically typed language (with optional static typing). Since MVEL is built on top of the JVM, which is a strongly typed, it is often necessary for MVEL to provide high-level type conversion.

To that end, MVEL provides an open and pluggable type conversion API in order to facilitate this.

Out of the box, MVEL comes with a full array of type converters that can handle the entire gambit of Java types, with special support for things like collections and the java.math.* libraries.

The org.mvel.DataConversion Class

The DataConversion class is the core of the entire API. It serves as the factory where data converters are registered and obtained for use by the runtime.

It contains three useful methods:

The first two methods are used by the compiler and runtime to actually perform conversions between types.

The third method allows you to programmatically register more conversion handler classes. Only one conversion handler can be registered per type. So if you replace the conversion handler for a built-in type, your conversion capabilities will be limited to what you implement in the replacement converter.

The org.mvel.ConversionHandler Interface

The conversion handler interface has two methods you must implement:

Each converter represents a target type for conversion to a particular data type. So in the case of say, an IntegerConverter, that converter must be able to accept values and return an an Integer. It does not work the other way around.

Why It's Needed, and How It's Used

MVEL's typing model is very loose and supports two models of typing: duck typing, and static typing. The model used is inferred by the actual script itself. Let's look an example:

In this particular MVEL script, we have declared two variables: list and index. And in this case we are using duck typing. The compiler looks at this script and deduces two things:

  1. list is type: java.util.ArrayList
  2. index is type: java.lang.String

Now this isn't exactly a good example, because who would purposefully pass a string to a method which accepts an int? But it demonstrates the automatic data conversion at work.

When MVEL tries to compile list.get(index), it will see that index is a string literal, and it will see that list.get() accepts an int. Therefore the compiler will call the data conversion API to ask it if it's possible to convert a String to an int. Surprisingly, the conversion API will say: yes, and attempt to parse the String as an int. Failing this, a conversion exception will be thrown.

It's more likely that you'll be taking advantage of int-to-long and int-to-double type conversions on a regular basis in your scripts, which can be very handy.

Powered by Atlassian Confluence