开发者

How to use Java varargs with the GWT Javascript Native Interface? (aka, "GWT has no printf()")

开发者 https://www.devze.com 2023-02-13 07:08 出处:网络
I\'m trying to quickly learn GWT as part of a new project.I found out that GWT doesn\'t implement Java\'s String.format() function, so there\'s no printf()-like functionality.I knew that some printf()

I'm trying to quickly learn GWT as part of a new project. I found out that GWT doesn't implement Java's String.format() function, so there's no printf()-like functionality. I knew that some printf() implementations exist for Javascript, so I figured I could paste one of those in as a GWT Javascript Native Interface function. I ran into problems, and decided I'd better make sure that the varargs values were being passed in correctly. That's where things got ugly. First, some example code:

// From Java, call the JSNI function:
test("sourceString", "params1", "params2", "params3");

....

public static native void test(Object... params) /*-{   
    // PROBLEM: this kills GWT!
    // alert(params.length);  

    // returns "function"
    alert(typeof(params));      

    // returns "[Ljava.lang.Object;@b97ff1"
    alert(params);
}-*/;

The GWT docs state that "calling a varargs JavaScript method from Java will result in the callee receiving the arguments in an array". I figured that meant I could at开发者_Python百科 least check params.length, but accessing that throws a JavascriptException wrapped in an UmbrellaException, with no real information. When I do "typeof(params)", it returns "function". As if that weren't odd enough, if I check the string value of params, it returns what appears to be a string version of a Java reference.

So, I guess I'm asking a few different questions here:

1) How do GWT/JSNI varargs actually work, and do I need to do something special to pass in values?

2) What is actually going on here?

3) Is there any easier way to get printf()-style formatting in a GWT application?


Your JSNI method is receiving the arguments but, unfortunately, can't do anything with them. Java arrays (varargs are implemented by constructing arrays of the passed arguments) are opaque when passed to JSNI methods. You can however achieve your goal with a JsArrayString:

public static native void test(JsArrayString strings) /*-{
  // strings is a normal JavaScript array of strings
}

And calling the method:

String[] jStrings = {"one", "two", "three"};
JsArrayString jsStrings = (JsArrayString)JsArrayString.createArray();

for (String s : jStrings) {
  jsStrings.push(s);
}

test(jsStrings);
0

精彩评论

暂无评论...
验证码 换一张
取 消