Java Reference
In-Depth Information
Example 8−2: Command.java (continued)
catch (InvocationTargetException ex) { // but handle the exceptions
throw new RuntimeException("Command: " +
ex.getTargetException().toString());
}
catch (IllegalAccessException ex) {
throw new RuntimeException("Command: " + ex.toString());
}
}
/**
* This static method creates a Command using the specified target object,
* and the specified string. The string should contain method name
* followed by an optional parenthesized comma-separated argument list and
* a semicolon. The arguments may be boolean, integer or double literals,
* or double-quoted strings. The parser is lenient about missing commas,
* semicolons and quotes, but throws an IOException if it cannot parse the
* string.
**/
public static Command parse(Object target, String text) throws IOException
{
String methodname; // The name of the method
ArrayList args = new ArrayList(); // Hold arguments as we parse them.
ArrayList types = new ArrayList(); // Hold argument types.
// Convert the string into a character stream, and use the
// StreamTokenizer class to convert it into a stream of tokens
StreamTokenizer t = new StreamTokenizer(new StringReader(text));
// The first token must be the method name
int c = t.nextToken(); // read a token
if (c != t.TT_WORD) // check the token type
throw new IOException("Missing method name for command");
methodname = t.sval;
// Remember the method name
// Now we either need a semicolon or a open paren
c = t.nextToken();
if (c == '(') { // If we see an open paren, then parse an arg list
for(;;) {
// Loop 'till end of arglist
c = t.nextToken();
// Read next token
if (c == ')') { // See if we're done parsing arguments.
c = t.nextToken(); // If so, parse an optional semicolon
if (c != ';') t.pushBack();
break;
// Now stop the loop.
}
// Otherwise, the token is an argument; figure out its type
if (c == t.TT_WORD) {
// If the token is an identifier, parse boolean literals,
// and treat any other tokens as unquoted string literals.
if (t.sval.equals("true")) {
// Boolean literal
args.add(Boolean.TRUE);
types.add(boolean.class);
}
else if (t.sval.equals("false")) { // Boolean literal
args.add(Boolean.FALSE);
types.add(boolean.class);
}
Search WWH ::




Custom Search