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.

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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 = [email protected]::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.

1 Comment

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?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.