Sunday, May 4, 2008

Magic of Multilanguage Environment

We need to create methods at runtime (say, based on some user input we need to construct an behavior in the form of methods) and associate/execute that methods in the context of particular existing object instance. How could we achieve this in Java?

1) Use features of mlvm. Currently it is in prototype stage. So we may have to wait for some time before being available as part of standard distribution.

2) We could use any of byte code engineering libraries and include a method in the class at runtime. But we are trying to include a method for a particular object instance of the class. Not in the class itself.

Hey, Javacript/Ruby very much allow adding new methods to a particular instance and good news is that we have matured Javascript (Rhino) and Ruby (JRuby) implementations in Java. You may be aware that Rhino javascript implementation is included as part of standard java 6 distribution. With the help of Rhino engine, we could take advantage of power of javascript and implement our scenario.

Include JDK_6_HOME/bin in your path.
Type jrunscript in command prompt.

var fr = new javax.swing.JFrame()
fr.title = "My Title"
fr.setSize(200, 200)
fr.show()

var fn_title = function(title_text) {this.title = title_text}
fn_title.call(fr, "My New Title")

"fn_title" is the method, that we have associated with "JFrame" instance "fr"

PS: Rhino engine is written in Java. How easy to simulate above behavior with our own java classes and byte code engineering? Look at these slides for answer.