简体   繁体   English

从JSNI调用Java方法

[英]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();
}-*/;

From Accessing Java Methods and Fields from JavaScript documentation: JavaScript文档中访问Java方法和字段

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) class-name :是在其中声明方法的类(或其子类)的标准名称。

  • 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 param-signature :是在JNI Type Signatures中指定的内部Java方法签名,但是没有方法返回类型的尾随签名,因为不需要选择重载

  • arguments : is the actual argument list to pass to the called method arguments :是传递给被调用方法的实际参数列表

Here are JNI Type Signatures: 这是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

In your case (no parameters) it would be: 在您的情况下(无参数)将是:

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

Replace your.package.name with a real package name. 用真实的包名称替换your.package.name

package org.example.foo;
public class Flipper {

  public native void flipName(String name) /*-{
    var re = /(\w+)\s(\w+)/;
    var s = name.replace(re, '$2, $1');
    this.@org.example.foo.Flipper::onFlip(Ljava/lang/String;)(s);
  }-*/;

  private void onFlip(String flippedName) {
   // do something useful with the flipped name
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM