Dev : Extensions : Example Code : Calling Java from JavascriptFrom MozillaZine Knowledge BaseThis page is currently notes of what I had to do to call Java from Javascript from Thunderbird. Here's an example from a blog: http://mozilla-firefox-extension-dev.blogspot.com/2004/11/calling-java-code-in-custom-jars-from.html var cl = new Packages.java.net.URLClassLoader( [ new Packages.java.net.URL( 'http://foo.net/bar.jar') ] ); var aClass = Packages.java.lang.Class.forName("HelloWorld", true, cl); var aStaticMethod = aClass.getMethod("getGreeting", []); var greeting = aStaticMethod.invoke(null, []); alert(greeting);
Calling showJavaConsole is very useful for debugging: var jvm = Components.classes["@mozilla.org/oji/jvm-mgr;1"].getService(Components.interfaces.nsIJVMManager); jvm.showJavaConsole(); Here's the code I use to log exceptions. JSUtil.getStackTrace doesn't always work. I haven't figured out why, so I do it last, wrap it in a try catch, and print out my own "rough" stack trace first. (The rough list has no line numbers.) Wrap all java calls in a try catch and log the exception. Mozilla doesn't always report them and when it does it doesn't give the stack trace, and it's usually wrapped in a meaningless exception. I think the java console logs all exceptions though, so maybe this isn't necessary if you use that. function logExc(e) { try { while(e != null) { debug(e); e = e.getCause(); } debug(netscape.javascript.JSUtil.getStackTrace(e)); } catch(exp) { debug("exception while logging exception"); debug(exp); debug("exception being logged"); debug(e); } }
|