File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes GWT and the fly likes Native method using JSNI Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Frameworks » GWT
Bookmark "Native method using JSNI" Watch "Native method using JSNI" New topic

Native method using JSNI

Sathiesh Kumar Vs
Ranch Hand

Joined: Oct 24, 2010
Posts: 31

I am using GWT and I have created a native method in 'MyClass' to define a Javascript function named myFunction

private native void myMethod(MyClass X) /*-{
$wnd['myFunction'] = function () {

This function 'myFunction' will be called onClick of a button and that calls the javaMethod in MyClass. This as such is working fine.

Now I want the name of the function that i define to be dynamic, i.e the name 'myFunction' should be set dynamically and the javascript function should be created with that dynamic name.

The purpose of this is, the code i have written is in a common class which will be used by many other classes. So when all the classes use the same code, there are methods created with the same name in the javascript and is not working properly.

Please suggest a good way to crack it.

Thanks and Regards,
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Not sure where to put this topic. Let's try the GWT forum.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Hardik Mishra

Joined: Sep 21, 2009
Posts: 3

Create a class which generates dynamic name on each call.

public class JSNIHelper {

private static int requestCounter = 0;

public static String registerCallbackFunction(MyClass obj) {

String dynamicName = "jsni" + (requestCounter++);
// you can write your own logic to generate dynamic name for

createDynamicFunction(obj, dynamicName);
return callbackName;

private native static void createDynamicFunction(MyClass obj, String dynamicName )/*-{
tmp = function( name ){
obj.@example.myclass::execute(Ljava/lang/String;)( name );

// Your Class where you will call
// Pass object of 'MyClass'

public void onClick(ClickEvent event) {
String callbackName = JSNIHelper.registerCallbackFunction(new MyClass() {

// do other things

Hope it will help....

Best Regards
Hardik Mishra
Software Engineer

Give a man a fish, and you feed him for a day. Teach a man to catch fish and you feed him for a lifetime.
I agree. Here's the link:
subject: Native method using JSNI
It's not a secret anymore!