Java Reference
In-Depth Information
If an expression matches the regular expression, the parse() method stores the
matched parts into respective instance variables.
Notice that the regular expression to match operands is not perfect. It will allow
several invalid cases, such as an operand having multiple decimal points, and so on.
However, for the purposes of this demonstration, it will do.
The getOperandValue() Method
The getOperandValue() method is used during an expression evaluation after the
expression has been parsed. If the operand is a double number, it returns the value by
applying the sign of the operand. Otherwise, it looks up the name of the operand in the
ScriptContext . If the name of the operand is not found in the ScriptContext , it throws a
RuntimeException . If the name of the operand is found in the ScriptContext , it checks if
the value is a number. It the value is a number, it returns the value after applying the sign
to the value; otherwise, it throws a RuntimeException .
The method does not support operands in hexadecimal, octal, and binary formats.
For example, an expression like “0x2A + 0b1011” will not be treated as an expression
having two operands with int literals. It is left to readers to enhance this method to
support numeric literals in hexadecimal, octal, and binary formats.
The eval() Method
The eval() method evaluates the expression and returns a double value. First, it parses
the expression if it has not already been parsed. Note that multiple calls to the eval()
parses the expression only once.
It obtains values for both operands, performs the operation, and returns the value of
the expression.
The JKScriptEngine Class
Listing 8-2 contains the implementation for the JKScript script engine. Its eval(String,
ScriptContext) method contains the main logic, as shown:
Expression exp = new Expression(script, context);
Object result = exp.eval();
It creates an object of the Expression class. It calls the eval() method of the
Expression object that evaluates the expression and returns the result.
The eval(Reader , ScriptContext) method reads all lines from the Reader ,
concatenates them, and passes the resulting String to the eval(String,
ScriptContext) method to evaluate the expression. Notice that a Reader must have only
one expression. An expression may be split into multiple lines. Whitespaces in the Reader
are ignored.
 
Search WWH ::




Custom Search