Apr 30, 2009

Instantiate Java class in JavaScript

I know I am mostly writing about C# and .NET and so on and you may wonder way do I write about java but I found this interesting and useful even in .NET projects.
I was playing with the mindfusion diagram latelly (you can check my posts under the Mind Fusion Diagramming in the blog categories) and found myself in a situation where I needed to instantiate a class from the mindfusion package (i think it was table cell but this doesn't matter right now).

So in order to instantiate Java class in JavaScript you may do this from the Packages object.
For example if you have a class like:
java.MyClass

you can instantiate it this way in javascript:

var myClass = Packages.java.MyClass();

Let's suppose the class has Name property, you can call it like this:

alert(myClass.Name);
// If the class has a property "Name", call it ...

Hope this helps somebody out there...
So long and thanks for al the fish ;)

NOTE : I haven't tested this under browsers other than Internet Explorer 7. Hopefully it will work ...

No comments: