Ankur Gupta
Ankur Gupta

Reputation: 58

In GWT how can we share objects between javascript and java?

I have a pojo in my class containing some methods to manipulate Maps and Arrays in java. This object is used in RPC calls to carry my configurations. I have a mechanism in which before making any RPC call I execute a javascript function. Now what I really want is to pass my configuration object to this javascript function and this javascript function can manipulate this configuration object and finally this manipulated object will be passed in my RPC call.

So how can I pass my java object to javascript and allow manipulating it?

Upvotes: 0

Views: 1545

Answers (1)

First, you cannot manipulate Java objects from javascript directly. But what you can do, is to export a set of static methods to javascript and use them to manipulate your objects. This is done in this way:

public void onModuleLoad() {
    exportHelloMethod(this);
}
public String exportedMethod(String name) {
    // Manipulate your java classes here
    // return something to JS
}
// Create a reference in the browser to the static java method
private native void exportHelloMethod(HelloClass instance) /*-{
  $wnd.hello = instance@[...]HelloClass::exportedMethod(Ljava/lang/String;);
}-*/;

Fortunately there is a library which allows exporting java methods and classes in a simpler way. It is gwt-exporter, and you have just to implement Exportable in your class and use a set of annotations so as the exporter generator does all the work.

@ExportPackage("jsc")
@Export
public class MyClass implements Exportable {
  public void show(String s){
  }
}

public void onModuleLoad() {
  ExporterUtil.exportAll();
}

Then in javascript you can instanciate and manipulate the class:

 var myclass = new jsc.MyClass();
 myclass.show('whatever');

Upvotes: 1

Related Questions