Java Reference
In-Depth Information
strategy evaluated by playing it against others. The score would then be
returned to the player.
At the server, the game program loads each waiting
Player
class, creates
an object of the new type, and runs its strategy against the game al-
gorithm. When the results are known, they are reported to the player
who submitted the strategy.
The communication mechanism isn't specified here, but it could be as
simple as electronic mail, with players mailing their classes and receiv-
ing the results by return mail.
The interesting part is how the game program loads the compiled class
files into its runtime system. This is the province of a
class loader,
which
must extend the abstract
ClassLoader
class and override its
findClass
method:
protected Class<?>
findClass(String name)
throws ClassNotFoundExcep-
tion
Locates the bytecodes representing the class
name
and loads
them into the virtual machine, returning the
Class
object cre-
ated to represent that class.
In our example, we would provide a
PlayerLoader
class to read the byte-
codes from the player classes and install each of them as a usable class.
The basic loop would look like this:
public class Game {
public static void main(String[] args) {
String name; // the class name
while ((name = getNextPlayer()) != null) {
try {
PlayerLoader loader = new PlayerLoader();
Class<? extends Player> classOf =
loader.loadClass(name).
asSubclass(Player.class);
Player player = classOf.newInstance();
Game game = new Game();