Dynamic class loading in Java

Sometimes in programming we need to do crazy things in order to create innovative stuff. One of craziest ones could be to write programs which can write its own code to improve their functionality.

At a recent project about bussiness games I had to allow non-programmer users to edit or create operators in order to make updating rules for their variables. Finally I decided to give them a easy drag and drop interface which they loved, but in the code side I had to create Java code, compile and load the resulting class in run time without rebooting the system. This is the code I used to load the operator classes once they were ready.

try {
  //This loads a class with the name operatorClassName
  BaseOperator operatorObject = (BaseOperator) Class.forName(“com.engage.operators.”+operatorClassName).newInstance();
operatorObject.setSources(sources);//Pass the sources to the object
  return operatorObject.calculateValues();
} catch (ClassNotFoundException ex) {
  System.out.println(operatorName + “is not installed in this system”);
}

As you can notice, I used a base class for all operators to have a common interface to interact with classes that in moment of writting this code I didn’t know about their existence. Of course you have to remember to extend this base class in each new operator.

And that’s all. This is a good mechanism to introduce the posibility to let your Java app to have plugins, or implement an easy command driven Java application by creating a class to process each command and a general controller to receive the command in a string form and load the implementing class dinamically.

Advertisement

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.