Java Reference
In-Depth Information
Interpreter
The Expression hierarchy is at the heart of the Interpreter pattern. It defines the grammar that can be used to
create and evaluate expressions. The Expression interface is the foundation for all expressions, and defines the
interpret method that performs an evaluation.
Table A-1 lists the interface and corresponding information.
Table A-1. Purpose of the Expression interface and its implementers
Expression
Common interface for all expressions
ConstantExpression
Represents a constant value
VariableExpression
Represents a variable value, obtained by calling a method on some class
CompoundExpression
A pair of comparison expressions that evaluate to a boolean result
AndExpression
The logical “and” of two expressions
OrExpression
The logical “or” of two expressions
ComparisonExpression
A pair of expressions that evaluate to a boolean result
EqualsExpression
P erforms an equals method comparison between the two expressions
ContainsExpression
Checks to see if the first String expression contains the second one
Example A.51 Expression.java
1. public interface Expression{
2. void interpret(Context c);
3. }
Example A.52 ConstantExpression.java
1. import java.lang.reflect.Method;
2. import java.lang.reflect.InvocationTargetException;
3. public class ConstantExpression implements Expression{
4. private Object value;
5.
6. public ConstantExpression(Object newValue){
7. value = newValue;
8. }
9.
10. public void interpret(Context c){
11. c.addVariable(this, value);
12. }
13. }
Example A.53 VariableExpression.java
1. import java.lang.reflect.Method;
2. import java.lang.reflect.InvocationTargetException;
3. public class VariableExpression implements Expression{
4. private Object lookup;
5. private String methodName;
6.
7. public VariableExpression(Object newLookup, String newMethodName){
8. lookup = newLookup;
9. methodName = newMethodName;
10. }
11.
12. public void interpret(Context c){
13. try{
14. Object source = c.get(lookup);
15. if (source != null){
16. Method method = source.getClass().getMethod(methodName, null);
17. Object result = method.invoke(source, null);
18. c.addVariable(this, result);
19. }
20. }
21. catch (NoSuchMethodException exc){ }
22. catch (IllegalAccessException exc){ }
23. catch (InvocationTargetException exc){ }
24. }
25. }
 
 
Search WWH ::




Custom Search