Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Build a Reflection-based Interpreter in Java

Java's support of reflection enables you to create an interpreter that executes commands interactively. This article 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.


advertisement
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 startServer:

static public String startServer( int port );

In general, each command has the format shown in Figure 1.

Figure 1: A Scripting Command

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: 10.0 and 20.0.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap