1

I know we can do this via DWR library to work with Java objects in Javascript. But I would like to know if we can actually instantiate Java Objects in Javascript, using plain Javascript objects?

I searched on the internet and found this link and this link which speaks about Packages object in Javascript. I even read that this object is a part of JS since JS 1.1, is that true?

But when I actually used var myClass = new Packages.myPackage.myClass(); , it says, Packages is not defined, obviously I am missing out something here.

For my use case I have to instantiate a Java Pojo in JS. Any clue folks on how to achieve this?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
First Blood
  • 235
  • 7
  • 21

2 Answers2

1

This feature depends on the JavaScript engine (i.e. the interpreter which runs the JavaScript). I haven't tried to do this in a browser but it might be possible when the Java plugin is enabled (which you shouldn't do for security reasons, at least not unconditionally).

The special object Packages is a feature of the Rhino engine, for example, which is a JavaScript interpreter that runs in a Java VM. The Packages has overloaded the accessor methods so when you write Packages.com.pany.Foo, it will internally look up the class and return something that wired the Java and the JavaScript worlds in a useful way.

You can find a tutorial here: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java

Aaron Digulla
  • 310,263
  • 103
  • 579
  • 794
0

You can create a Java object and assign it to a variable in JavaScript with the help of the new keyword. When you create an instance of a Java class, JavaScript automatically creates a JavaObject object. For example, you can instantiate a Java String from JavaScript and assign it to a variable. Then you can use the dot operator to access the object’s length()

var myString=new java.lang.String("Test String");
alert(myString.length()); //prints 11

You can follow this link for more information http://www.sitepoint.com/connect-java-to-javascript-with-liveconnect/

Aaron Digulla
  • 310,263
  • 103
  • 579
  • 794
rk rk
  • 306
  • 1
  • 8