我有这个方法:
public void testJSNI2(){
String x = "test";
}
我可以像这样访问这个方法:
helloJsni.@com.jsni.client.HelloJSNIImpl::testJSNI2(Ljava/lang/String;)
但是如何访问在x
方法中定义的 String 呢?
答案是不正确的。JavaScript 和 Java 的行为并不相同。Person 可以在 JSNI 的帮助下访问 js 中的任何字段:
public class JSNIExample {
String myInstanceField;
static int myStaticField;
void instanceFoo(String s) {
// use s
}
static void staticFoo(String s) {
// use s
}
public native void bar(JSNIExample x, String s) /*-{
// Call instance method instanceFoo() on this
this.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);
// Call instance method instanceFoo() on x
x.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);
// Call static method staticFoo()
@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s);
// Read instance field on this
var val = this.@com.google.gwt.examples.JSNIExample::myInstanceField;
// Write instance field on x
x.@com.google.gwt.examples.JSNIExample::myInstanceField = val + " and stuff";
// Read static field (no qualifier)
@com.google.gwt.examples.JSNIExample::myStaticField = val + " and stuff";
}-*/;
}
你可以在这里看到这个:http: //www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html
您无法访问该变量x
,因为它在方法的范围内,就像您无法在 Java 代码中访问它一样。