Limbo Overview3
3. The API3.1. Getting Started
Let's start with a simple example first:
Example 2. Simple expression
Expression<Integer, Person>doubleAge = Expressions.from(Person.class).toInteger("age * 2");Person wilfred = new Person();wilfred.name = "Wilfred";wilfred.age = 35;assert 70 == doubleAge.eval(wilfred);
In the first line, we build the
Expression
instance. Since the expression is based on a
Person
object, the
from(...)
method takes
Person
class reference. After that, we specify that we expect an integer result, andpass the expression at the same time. (The builder methods actually have a couple of other options, but we willleave that out for now.)Once the
Expression
has been built, evaluating is simply calling
eval(...)
on the expression, passing in the
Person
instance. And - like you could have expected - the result is 70. Note there is no cast in order to compare to70, courtesy of the use of generics and auto unboxing.
3.2. The ReferenceContext
I said before that Limbo is capable of binding to
anything
capable of representing itself as 'things' with namedattributes and numbered items. Let me refine that: it is capable of binding to anything for which you canimplement a
ReferenceContext
. So, when in Example 2, “Simple expression” you passed in a Person class,under the hood, Limbo wrapped that inside a ReferenceContext.Now, if you ever used an expression language like the JSP EL, then you are probably aware of a similar mechanismin that expression language. JSP EL has a
VariableResolver
. Your EL expression can be evaluated againstanything, as long as there is a
VariableResolver
capable of resolving the named things.One of the differences between Limbo's ReferenceContext and JSP EL's VaribleResolver is that theReferenceContext is parameterized with type of context passed in at evaluation time. Typically, with JSP EL, youwill evaluate your expression against a context of of type
java.lang.Object
. The Java compiler will not be ableto verify if the subtype of
java.lang.Object
you pass in is actually something against which you can evaluatethe expression.If you are creating an expression in Limbo, you will always need to construct that expression parameterized
ReferenceContext
, in which the type parameter is the type of object on which you can apply the expression.So if you have an expression you want to evaluate against an instance of
Person
, you need to construct the
Expression
based on a
ReferenceContext<Person>
.