First, you have to override getDefaultValue in Sumit. This is needed to convert object to string from javascript.
package sumit2;
import org.mozilla.javascript.ScriptableObject;
public class Sumit extends ScriptableObject {
public String getClassName(){
return "Sumit";
}
public void foo() {
System.out.println("Sumit!!!!!!!");
}
@Override
public Object getDefaultValue(Class<?> typeHint) {
return toString();
}
}
And then, you will get following error message:
js: uncaught JavaScript runtime exception: TypeError: Cannot find function foo in object sumit2.Sumit@1bf6770.
**NOTE: The exception "Cannot find default value for object.” was caused when displaying exception above. The string value "sumit2.Sumit@1bf6770" is produced by calling getDefaultValue
Second, javascript cannot call java methods of objects extended from ScriptableObject. If you want to call foo from javascript, override get(String, Scriptable) like following:
package sumit2;
import jp.tonyu.js.BuiltinFunc;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class Sumit extends ScriptableObject {
public String getClassName(){
return "Sumit";
}
public void foo() {
System.out.println("Sumit!!!!!!!");
}
@Override
public Object getDefaultValue(Class<?> typeHint) {
return toString();
}
@Override
public Object get(String name, Scriptable start) {
if ("foo".equals(name)) {
return new Function() {
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args) {
foo();
return "Return value of foo";
}
/** ...Implement all methods of Function other than call **/
};
}
return super.get(name, start);
}
}
And you will get:
Sumit!!!!!!!
Return value of foo
I think the part
/** ...Implement all methods of Function other than call **/
is annoying. I recommend to create an adapter class which implements Function and overrides all methods of Function with empty statements.