0

Say I have a Java class Course that has some method testMethod. How do I expose this functionality such that I can interact with it using hand-written JavaScript as follows:

someCourse.testMethod();

where someCourse is passed directly from the Java code via a native method, like:

private native void AssociateCourse(Course course) /*-{
    someCourse = course;
}-*/;

The main issue I am having in achieving this is that GWT does not provide any way for me to access the prototype of the Course constructor. For example, the following is invalid:

private native void Expose() /*-{
    $wnd.Course = @mypackage.Course;
}-*/;

because it expects it to access some field, not the whole thing.

I would like to avoid using a library like gwt exporter because I feel that having to incorporate that into my source code which handles application logic will make it difficult to separate those two aspects of my code, which will be a bad thing if the code were shared between a GWT project like this and an Android application, for example.

Samuel Goodell
  • 600
  • 2
  • 9

2 Answers2

0

If you use GWT 2.7+ you can use the new JSInterop. It is hidden behind a compiler flag, but works quite well.

It is still experimental and may change in future releases.

Take a look at this demo: https://www.youtube.com/watch?v=wFMD1GXR2Tg

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
0

Well there are different ways you can accomplish your problem, and it depends as well of the amount of stuff you have to expose.

If it is just a couple of methods I would use pure JSNI or gQuery.

As the answer to your question, in your class constructor you can expose methods for new instances (I would not modify the java class prototype though):

public class Course  {
    public Course() {
        exportMethods(this);
    }
    public String testMethod(String s) {
        return s;
    }
    private native void exportMethods(Course c) /*-{
        this.testMethod = c.@mypackage.Course::testMethod(*);
    }-*/;
}

As you say gwt-exporter implies to include a dependency, but if you are going to deal with a lot of exported methods, properties, and callbacks it is worth.

The new stuff JsInterop available in 2.7.0 is very experimental, it lacks a lot of features and you have to enable it using a experimental compiler flag in the compiler, it would be almost usable in 2.8.0 but still experimental until 3.0.0, so I would not trust on it for production projects.

Community
  • 1
  • 1
Manolo Carrasco Moñino
  • 9,723
  • 1
  • 22
  • 27
  • Would this result in a redundant implementation of the `testMethod` on every instance of a Course, rather than just one on some shared object like its prototype? – Samuel Goodell May 15 '15 at 07:37