javascript - 从 JSNI 调用 Java 方法

标签 javascript gwt jsni

我有一个类,例如:

public class Person {

    private String name;

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

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

如果我这样调用方法(或者我的无知或错误的地方),它会起作用吗:

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

最佳答案

来自 Accessing Java Methods and Fields from JavaScript文档:

语法是:

[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

这里是 JNI 类型签名:

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

在你的情况下(没有参数)它将是:

public native void someMethod (Person person) /*-{
    person.@your.package.name.client.Person::sayName()();
}-*/;

your.package.name 替换为真实的包名。

关于javascript - 从 JSNI 调用 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048830/

相关文章:

javascript - Python索引错误列表索引超出范围

java - 获取当天的开始时间和结束时间

java - GWT 和 JSNI 将 Javascript 按钮添加到 HTML 面板中

GWT JSNI javascript 到 Java 不工作

java - GWTQuery 实时模糊不起作用

javascript - gwt jsni变量名混淆

java - GWT JSNI调用小程序方法

javascript - 从 getElementsByClassName() 函数数组中获取 'this' 元素

javascript - jQuery 在 Canvas 上的特定幻灯片的 div 函数中淡入淡出(使用 js)

javascript - 如何在 jQuery 中的 href 之前显示图像 src