// --------------------------------------------------------------- // MethodNode - Subclass of Node representing a function call, all // our functions take one argument (a double) and // return a double, like: sin, cos, sqrt, etc. // --------------------------------------------------------------- import java.lang.reflect.Method; import java.util.HashMap; public class MethodNode extends Node { public MethodNode(String name, Node arg) { mName = name; mArg = arg; } public double evaluate(HashMap env) throws Exception { // ----------------------------------------------------- // If mMethod is null, this is our first time through // evaluate - try to set that member variable // ----------------------------------------------------- if(mMethod == null) { if((mMethod = mLookup.get(mName)) == null) throw new Exception("Unknown method: '" + mName + "'"); } Object result = mMethod.invoke(null, mArg.evaluate(env)); return(((Double)result).doubleValue()); } public String toString() { return(mName + "(" + mArg.toString() + ")"); } private String mName; private Node mArg; private Method mMethod; private static HashMap mLookup = new HashMap(); private static Method getMethod(String name) { Method theMethod = null; try { theMethod = Class.forName("java.lang.Math").getDeclaredMethod(name, double.class); } catch(Exception e) { System.out.println(e); } return(theMethod); } static { mLookup.put("abs", getMethod("abs")); mLookup.put("acos", getMethod("acos")); mLookup.put("asin", getMethod("asin")); mLookup.put("cbrt", getMethod("cbrt")); mLookup.put("ceil", getMethod("ceil")); mLookup.put("cos", getMethod("cos")); mLookup.put("cosh", getMethod("cosh")); mLookup.put("exp", getMethod("exp")); mLookup.put("floor", getMethod("floor")); mLookup.put("log", getMethod("log")); mLookup.put("log10", getMethod("log10")); mLookup.put("round", getMethod("round")); mLookup.put("sin", getMethod("sin")); mLookup.put("sinh", getMethod("sinh")); mLookup.put("sqrt", getMethod("sqrt")); mLookup.put("tan", getMethod("tan")); mLookup.put("tanh", getMethod("tanh")); } }