2

How I can send Java object from JavaScript to Java? LiveConnect allow us to get Java objects from calling applet method. i.e. we can have following method in applet:

public MyClass getMyClass() { return new MyClass(); }`

where MyClass is:

public class MyClass implements Serializable {
   private String a;
   private String b; //getters, setters
}

and in JS access this objects using:

applet.getMyClass().someMethod();

But how I can pass object from JavaScript (json object I think) to java method (not as json string)? i.e. I want to have in applet method like this:

public void myMethod(MyClass var)

and from JavaScript call this method passing parameter of type MyClass. How to build MyClass object in JS? I hope LiveConnect do conversion from JSON to Java object automatically..

WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
  • did u try passing json object ? – vels4j Nov 30 '12 at 12:06
  • Hi. Just wondering. Did any of the answers help? Have you made any progress? Oh, and good luck with your project :-) I love it when languages talk to each other! – Miltos Kokkonidis Dec 03 '12 at 07:53
  • @MiltiadisKokkonidis I decide to go in another way, so I didn't test your solution. But seems your solution is work, so I mark your answer as accepted. Thanks. – WelcomeTo Dec 03 '12 at 13:40

2 Answers2

2

I believe this should give you a good idea about how to go about this.

import netscape.javascript.*;

public class MyClass implements Serializable {
public String a;
public String b;

    public JavaDog(JSObject o) {
        this.a= (String)o.getMember("a");
        this.b = (String)o.getMember("b");
    }
}

Then you use new Packages.MyClass(yourJavaScriptObject) to create the object you want to pass to Java.

More information here:

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/LiveConnect_Overview

Miltos Kokkonidis
  • 3,888
  • 20
  • 14
0

Java LiveConnect documentation says :

When a Java object which was previously returned to the JavaScript engine is passed back to Java, the object is simply checked for assignment compatibility with the target type. The only exception to this rule is automatic conversion to java.lang.String.

vels4j
  • 11,208
  • 5
  • 38
  • 63
  • Note: `which was previously returned to the JavaScript engine is passed back to Java` I don't return any value from method. I want pass a parameter to applet method of type `MyClass`. – WelcomeTo Nov 30 '12 at 12:16
  • 1
    My question is how can you create an instance object for `MyClass` in java script likey `MyClass myClass = new MyClass()` – vels4j Nov 30 '12 at 12:24