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.


Use your interfaces as protoypes

In one hand, the majority of current IDEs (Integrated Development Environments) for visual languages come with an elegant graphic User Interface Designer which let the process of designing interfaces to be a piece of cake.

In the other hand the creation of prototypes is a commonly used requirement-fetching technique that let the developers to test if the interface and functionality they are designing meets the users expectations.

In some cases, a piece of paper with some lines representing the user interface will be enough prototype for our project, but in the cases it is not enough, you will need a prototyping tool to draw interface images and simulate the flow between system screens with fake data shown on them.

I have seen some teams to use PowerPoint, Visio or Omnigraffle as a prototyping tool, and they generate amazing prototypes really close to the final interface, other teams use dedicated prototyping tools, but.. what if you use your cool IDE’s User Interface Designer to do the same?

You can create the screens and write the minimal methods to navigate between screens or initialize some fake data to show in the prototype. You will obtain the same with some advantages:

  1. Your prototype is just identical to your final user interface, without surprises for the users or bad interpretations.
  2. You can reuse your prototype as final interface without modifications to start developing your wonderful application.
  3. You can’t create prototypes that show amazing functionality your final interface can’t do, and your prototypes can do whatever your final interface needs to do.
  4. You haven’t to do the work twice, as in the moment you finish your prototype you finish your user interface.
  5. You can create your prototypes as fast as with any other prototyping tool, with just drag and drop.

Think about that and start saving some time to make your boss happier than ever.

These are some links with information about some IDEs or User Interface Designers available for commonly used languages and platforms:

  • Netbeans IDE: AWT and Swing user interfaces for Java SE
  • Eclipse IDE: SWT for Java (Don’t forget to install SWT plugin)
  • Qt Designer: Design Qt interfaces for your Java or C++ applications.
  • Xcode and Interface Builder: Design your Cocoa or Carbon application interfaces for Mac OS X or iPhone.
  • Visual Studio: You can do the trick even in Windows for .NET or C++ languages, but.. under your responsability.
  • Glade: Design your GTK+ interfaces for C Gnome programs

If you know other good interface designers I’ll be glad to add them in this list, just tell me about it 😉

Swap your variables without a temp variable

I clearly remember that first course programming class in which the teacher said to us – “…If you need to swap the values of two variables, you always need a third temporary variable to hold the value of the first one while you are setting the value of the second one over the first one…” – In this moment it seemed to be right and it was marked over stone in my mind. In C code it is something like that:

int a,b,temp;

/*The classic swap code*/

/*Values have been happily swapped! (a==2 && b==1)*/

It was ok until I was having a dinner with some friends from the university and one of them said – “..hey! I was  reading a open source related book and I saw a cool method to swap two variable values without to use a third one!” – He didn’t remember the exact code, only that the technique has XOR operations involved. When I arrived home I ran to my bash shell and started to write a few C lines until I rediscovered the trick. It is really cool, uses the same number of operations but a variable less:

/*The swap code (Initialization are the same) */

/*That’s all! Your variables swapped magically*/

I expect this simple trick make you as happy as it made to me 😉

The cat ate my Scope

If you are one of these JavaScript developers who likes to use an Object Oriented approach, using JavaScript constructors, I’m sure you have had a lot of headaches when you have tried to call some object’s method from setInterval() or setTimer() JavaScript functions. The problem is that when your method is called, it is called from the window object scope, losing your object’s one.

To avoid this problem we will introduce a solution in two steps, the first is to obtain a reference to your object instance, which is enough for some needs, and the second is to call your method from the object’s scope, which is needed to access the private part of your object. Here we go:

1. Remember that in JavaScript functions can have properties too, so you can save your object instance in a property of your favourite method and then access this property trought arguments.callee object which is a reference to the current function. See the following example:

//Object constructor
var MyObject = function(){
  this._periodicMethod = function(){
    var objectInstance = arguments.callee._scope;
    //Do the timed action over the objectInstance..
  this._publicMethod._scope = this;

  //Set the timer
  window.setInterval(this._publicMethod,10000); //Call the method every 10 seconds.

2. Using this method you have obtained a reference to your object, so you can already access its public interface. That could be enough for some uses, but sometimes we need to update private parts of our objects, so we actually need to operate from within the object. To ensure your method is working with the correct scope you can add the following check to your method code:

this._periodicMethod = function(){
  if(this != arguments.callee._scope){
     return arguments.callee.apply(arguments.callee._scope,arguments); 
  //Do the private stuff…

Take care with this last method, as it won’t work with older navigators (IE 5.0 or less) whose don’t support the apply method. You can see other techniques to recover your scope in this blog, but this one is the fastest and easier.

Object oriented JavaScript

JavaScript was not invented in an Object Oriented way as most programmers know it, that is there is no concept of ‘class’ in JavaScript. Anyway we can use and create objects as a list of key and values in the next way:

  field: ‘value’,
  operation: function(){
    //Do something

We can go a step beyond simulating the constructors we all know from other languages, the trick is to create functions which make object instances for us. The first thing we have to know is that in JavaScript every function has a context object called this, and the second is that it exists a new operator to create new function instances. Using both concepts we can construct a function which acts as a class. An example is better than a thousand words, I think its enough clear:

var MyClass = function(constructorParam){      

  this.publicField = constructorParam;

  this._privateField = constructorParam; //Note the _ symbol to make it private

  this.publicMethod = function(param1,param2){
    this._privateMethod(param1); //The function can only be called from within object’s functions
    //Do something else..

  this._privateMethod = function(param1){
    //Do something private

Once that code is included in your page you can use your fake class to work in JavaScript in a fashionable object oriented way:

var myInstance = new MyClass(‘some value’,‘some other value’);
var theSomeValueString = myInstance.publicField;
myInstance.publicMethod(theSomeValueString,‘a third value’);

I wish this trick help you to mantain your AJAX code a bit more organized. See you soon!