Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Build dynamically extensible applications

Find out how to build programs that you can extend dynamically -- even while they execute

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 3

The tools you'll need

Let's stop for a moment and look at the relevant pieces in the Java class library.

java.lang.Class

Instances of class Class represent classes and interfaces in a Java application. The Java virtual machine (JVM) usually manipulates classes behind the scenes; however, a program can directly manipulate classes via instances of the Class class.

Here is the public interface to class Class.

public final class java.lang.Class extends java.lang.Object
{
    public static Class forName(String className);
    public ClassLoader getClassLoader();
    public Class [] getInterfaces();
    public String getName();
    public Class getSuperclass();
    public boolean isInterface();
    public Object newInstance();
    public String toString();
}


We only need to look at the forName() and newInstance() methods. We'll deal with the forName() method first.

static Class forName(String className)

The forName() method returns the Class instance associated with the class with the specified class name. It loads the class into the executing program via the currently active class loader. The className parameter can name any class -- even one that does not exist currently. If the forName() method cannot find the named class, it throws a ClassNotFoundException.

Now let's take a look at the newInstance() method.

Object newInstance()

The newInstance() method creates a newly allocated instance of the class represented by the Class instance. Because this is done exactly as if by a new expression with an empty argument list, the class must define a no-arg constructor. If the newInstance() method cannot instantiate the class for any reason, it throws an InstantiationException. If the class or constructor is not accessible, it throws an IllegalAccessException.

Putting the tools to use

I stated earlier that this technique is easy to use. Now I intend to prove it. Here's all of the code necessary to dynamically load a class file into an executing application and create an instance of the class:

Object voila(String str)
{
   Object o = null;

try { Object o = Class.forName(str).newInstance(); } catch (Exception e) { System.out.println(e); }
return o; }


The try..catch statement is necessary in order to catch any errors or exceptions that are raised during loading and instantiation.

Notice how the string is passed down. Any string is possible as long as it names a valid Java class. The string can be obtained in any number of ways: The user can input it, the program can read it from a configuration file, or the user can pass it in on the command line. In short, the program doesn't have to know its value at compilation time.

If you want to interact with the string, you'll probably want to cast it to an instance of a class of the appropriate type. The following code shows how:

Foo f = null;

if (o instanceof Foo) { f = (Foo)o; }


This last step illustrates one of the limitations of this technique: The new class must either be a subclass of a class known to the program at compile time, or it must implement an interface known to the program at compile time. Although it's possible to load any class (because all classes technically are subclasses of the Object class), it's not particularly useful; while classes can be dynamically specified, their methods cannot. This limitation is one of the reasons the Introspection API was introduced as part of Java 1.1.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (1)
Login
Forgot your account info?

GreatBy Anonymous on March 30, 2009, 9:27 amreally helpfull, hope its still usable today :)

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources
  • Browse the documentation for class Class online http://www.javasoft.com/products/jdk/1.0.2/api/java.lang.Class.html
  • See how dynamic extensibility is handled in TCL http://sunscript.sun.com/man/tcl8.0/TclCmd/load.htm
  • See how dynamic extensibility is handled in PERL ftp://ftp.cis.ufl.edu/pub/perl/CPAN/doc/manual/html/pod/perlmod.html
  • See how dynamic extensibility is handled in Python http://www.python.org/doc/ext/node21.html#SECTION00400000000000000000
  • Download this article and the complete source code as a gzipped tar file http://www.javaworld.com/javaworld/jw-09-1997/howto/jw-09-howto.tar.gz
  • Download this article and the complete source code as a zip file http://www.javaworld.com/javaworld/jw-09-1997/howto/jw-09-howto.zip
  • Previous How-To Java articles