Dev : Extensions : Example Code : Calling Java from Javascript: Difference between revisions
No edit summary |
No edit summary |
||
Line 26: | Line 26: | ||
</pre> | </pre> | ||
http://www.xulplanet.com/references/xpcomref/ifaces/nsIJVMManager.html#method_showJavaConsole | http://www.xulplanet.com/references/xpcomref/ifaces/nsIJVMManager.html#method_showJavaConsole | ||
Here's the code I use to log exceptions. 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. (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. | |||
<pre> | |||
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); | |||
} | |||
} | |||
</pre> |
Revision as of 23:19, 26 October 2005
This page is currently notes of what I had to do to call Java from Javascript.
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);
In order to write to the file system, I had to add this to the javascript code: java.lang.System.setSecurityManager(null);
I could read a jar from the filesystem without a problem.
Calling showJavaConsole is very useful for debugging:
var jvm = Components.classes["@mozilla.org/oji/jvm-mgr;1"].getService(Components.interfaces.nsIJVMManager); jvm.showJavaConsole();
http://www.xulplanet.com/references/xpcomref/ifaces/nsIJVMManager.html#method_showJavaConsole
Here's the code I use to log exceptions. 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. (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.
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); } }