cripting languages exist because some programming tasks are both simple and important, and carrying them out with a language that doesn't tax the mind as much as a system programming language sometimes will is beneficial. (See Sidebar: Scripting vs. Programming
for a full explanation of the differences between scripting languages and programming languages.) Although Java is most decidedly a programming language (it is typed, highly structured, and compiled), don't you sometimes wish you could do scripting in Java, or something close to Java?
Thanks to the Reflection API, you can. Using the Reflection API, you can run methods dynamically. Java's support of reflection enables you to create an interpreter that executes commands interactively. This article describes a system you can use to build an interpreter into your application. It demonstrates how to build a reflection-based system that allows simple scripting of Java programs without having to install a special-purpose scripting language. It also provides a downloadable sample program. This solution can allow you to create simple control scripts for your Java programs.
The Scripting "Language"
Before I get to the implementation, let's take a look at the "language." I put the word language in quotes because this language is so crude it hardly merits the term. It has no control structures, no types, no variables, no keywords, and no expressions. It simply allows you to call a Java method. Nevertheless, it constitutes a language, which makes our implementation an interpreter.
Here's an example of a command in this language:
TinyChatServer startServer 5000
This command starts up a chat server listening on port 5000. The chat server is implemented by a class called
TinyChatServer, which has a method called
static public String startServer( int port );
In general, each command has the format shown in Figure 1.
Each command consists of a class name, a method name, and one or more arguments. Here's another example of a command:
Calculator add 10.0 20.0
Our interpreter interprets this command by calling the
add method of the
Calculator class, and passing it two arguments: