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
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.