0

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?

1 Answers1

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');
Manolo Carrasco Moñino
  • 9,723
  • 1
  • 22
  • 27
  • Does the exported object have to originate in javascript? Because if not then that's not what he's asking (and I have a similar problem). – rjcarr Dec 20 '13 at 00:25
  • The exported method/class is coded in java in the same way you do things in gwt, but exporting it to javascript, means that you can instanciate java classes from javascript or call java methods from javascript. Is this what you are asking? – Manolo Carrasco Moñino Dec 20 '13 at 08:15
  • My understanding is the poster wants to create objects in java code and then manipulate them in javascript. Your examples don't describe that nor where you say "you can instanciate (sic) java classes from javascript", which is just the opposite of that. I'm interested because I want to also create objects in java and manipulate them in javascript but can't figure out how to do it. I posted this question but haven't gotten any feedback, can you help? http://stackoverflow.com/questions/20709611/can-java-objects-be-accessed-from-javascript-in-gwt – rjcarr Dec 24 '13 at 01:25
  • You need some exported class which methods returning exportable java objects created in java. – Manolo Carrasco Moñino Dec 26 '13 at 12:56