THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

To make this work, you would provide a Player abstract class that players would extend to implement their
strategy. When players were ready to try their strategy, they would send the compiled class's bytecodes to
your system. The bytecodes would need to be loaded into the game and the 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 algorithm. 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 receiving 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
ClassNotFoundException

Locates the bytecodes representing the class name and loads them into the
virtual machine, returning the Class object created to represent that class.

In our example, we would provide a PlayerLoader class to read the bytecodes 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();
player.play(game);
game.reportScore(name);
} catch (Exception e) {
reportException(name, e);
}

Free download pdf