Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help >  Languages >  Java

Dynamic Class Loading in Java

This article aims to explain how to dynamically load classes at runtime with Java. In doing so it will illustrate the use of package, interface, Exceptions, abstract classes, etc, with Vectors and Hashtables thrown in. Some knowledge of Java is assumed. Most of the code originates from http://www.pramodx.20m.com/dynamic_class_loading_in_java.htm for which much thanks.

Introduction

Plug-in architectures offer flexibility for both the programmer and the user - extra functionality can be added to a program without the program having to be changed. Java has mechanisms to support this approach. This example is based on a situation where a text file will be read in and analysed in various ways, some of which may not be foreseeable by the programmer. When the program is run, it will load in the available plug-ins. The plug-ins need to conform to rules laid down by the main program but within those limits there's still some flexibility.

The type of arguments these detectors need may depend on what the detectors are looking for. In the example provided the plug-in is looking for a certain poetry form where the syllable-per-line information is needed. The main program can ask plug-ins what type of arguments are required.

Concepts

Before we look at the code, some terms and concepts are worth previewing

The Code

The code is divided into a number of files.

Plugin requirements

Further plugins can be added. They need to

Compiling

If you're going to try this example out, you'll have to create a directory named DetectorUser. In that create a directory named Detectors. The DetectorUser directory will store the main sources and the Detectors directory will store the plug-ins. Set your CLASSPATH environment variable to the parent directory of DetectorUser. Then compile the files in the order they're presented here. Run by going to the parent directory and typing java TextPatterns.PatternDetector

The top-level PatternDetector extends DetectorCreator so that it can load plug-ins. SyllableFormDetection is the sample plug-in provided. Loading it calls the plug-in's nameless block which in turn calls the plug-in's factory (which extends DetectorFactory).

© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: January 2004