Search code examples
javascriptgwtjsni

Calling Java method from JSNI


I have a class, for instance :

public class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void sayName() {
        System.out.println(name);
    }
}

Does it would be work if i call method like this (or where my ingorance or mistake):

public native void someMethod (Person person) /*-{
    person.sayName();
}-*/;

Solution

  • From Accessing Java Methods and Fields from JavaScript documentation:

    The syntax is:

    [instance-expr.]@class-name::method-name(param-signature)(arguments)
    
    • instance-expr. : must be present when calling an instance method and must be absent when calling a static method

    • class-name : is the fully-qualified name of the class in which the method is declared (or a subclass thereof)

    • param-signature : is the internal Java method signature as specified at JNI Type Signatures but without the trailing signature of the method return type since it is not needed to choose the overload

    • arguments : is the actual argument list to pass to the called method

    Here are JNI Type Signatures:

    Type Signature               Java Type
    Z                            boolean
    B                            byte
    C                            char
    S                            short
    I                            int
    J                            long
    F                            float
    D                            double
    L fully-qualified-class ;    fully-qualified-class
    [ type                       type[]
    ( arg-types ) ret-type       method type
    
    For example, the Java method:
    
    long f (int n, String s, int[] arr); 
    has the following type signature:
    
    (ILjava/lang/String;[I)J
    

    In your case (no parameters) it would be:

    public native void someMethod (Person person) /*-{
        [email protected]::sayName()();
    }-*/;
    

    Replace your.package.name with a real package name.