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

Posted by markerikson on Stack Overflow See other posts from Stack Overflow or by markerikson
Published on 2011-02-22T23:23:05Z Indexed on 2011/02/22 23:25 UTC
Read the original article Hit count: 377

Filed under:
|
|
|
|

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 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?

© Stack Overflow or respective owner

Related posts about java

Related posts about gwt