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?

6
  • 3
    No, Java and JavaScript are two very different things, despite the similar names.
    – bfavaretto
    Apr 11, 2013 at 22:07
  • 11
    Java is to JavaScript as Car is to Carpet! Apr 11, 2013 at 22:08
  • Yep, I know those two are different entities. I've been working with them since many years now. But, it just happened to by my use case, so I was wondering if there is any work around for this case! Apr 11, 2013 at 22:09
  • No, as you have mentioned yourself, you are gonna need something like DWR or GWT, etc. Apr 11, 2013 at 22:22
  • You could create the serialised form of the Java object. When you deserialise it the JVM won't care where it was created.
    – BevynQ
    Apr 11, 2013 at 22:31

2 Answers 2

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

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.