Java Reference
In-Depth Information
Example 8−2: Command.java (continued)
else {
// Assume its a string
args.add(t.sval);
types.add(String.class);
}
}
else if (c == '"') {
// If the token is a quoted string
args.add(t.sval);
types.add(String.class);
}
else if (c == t.TT_NUMBER) { // If the token is a number
int i = (int) t.nval;
if (i == t.nval) { // Check if its an integer
// Note: this code treats a token like "2.0" as an int!
args.add(new Integer(i));
types.add(int.class);
}
else { // Otherwise, its a double
args.add(new Double(t.nval));
types.add(double.class);
}
}
else { // Any other token is an error
throw new IOException("Unexpected token " + t.sval +
" in argument list of " +
methodname + "().");
}
// Next should be a comma, but we don't complain if its not
c = t.nextToken();
if (c != ',') t.pushBack();
}
}
else if (c != ';') { // if a method name is not followed by a paren
t.pushBack();
// then allow a semi-colon but don't require it.
}
// We've parsed the argument list.
// Next, convert the lists of argument values and types to arrays
Object[] argValues = args.toArray();
Class[] argtypes = (Class[])types.toArray(new Class[argValues.length]);
// At this point, we've got a method name, and arrays of argument
// values and types. Use reflection on the class of the target object
// to find a method with the given name and argument types. Throw
// an exception if we can't find the named method.
Method method;
try { method = target.getClass().getMethod(methodname, argtypes); }
catch (Exception e) {
throw new IOException("No such method found, or wrong argument " +
"types: " + methodname);
}
// Finally, create and return a Command object, using the target object
// passed to this method, the Method object we obtained above, and
// the array of argument values we parsed from the string.
return new Command(target, method, argValues);
}
Search WWH ::




Custom Search