Dev : Extensions : Example Code : Calling Java from Javascript

From MozillaZine Knowledge Base
Revision as of 18:42, 22 April 2015 by Tanstaafl (talk | contribs) (removed link to xulplanet)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

This page is currently notes of what I had to do to call Java from Javascript from Thunderbird.

Here's an example from a blog:

   var cl = new

   var aClass ="HelloWorld", true, cl);
   var aStaticMethod = aClass.getMethod("getGreeting", []);
   var greeting = aStaticMethod.invoke(null, []);

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[";1"].getService(Components.interfaces.nsIJVMManager);

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) {
            e = e.getCause();
    } catch(exp) {
        debug("exception while logging exception");
        debug("exception being logged");

I'm still trying to figure out how to get my classes in the regular classpath so I can access them with "Packages" and not use reflection. I tried setting the classpath and it doesn't work. If you use the URLClassLoader to create an instance of a class, you can call methods on it normally. So you can say "var myclass = class.newInstance()" and then call instance methods on my class. That way you don't have to use reflection for everything.

Sometimes Javascript objects get passed to Java as JSObjects. I think it's doing that for me because of the reflection, since the URL[] works in the classloader example. JSObject is defined in $JAVA_HOME/jre/lib/plugins.jar. It's documented here:

To get the Java plugin working in Thunderbird, I had to make a ".plugins" directory in ~/.mozilla (not ~/.thunderbird), and symlink in that directory. Make sure you use one compiled with the same gcc as the thunderbird compile. It also seemed to care that it was a symlink and not a copy of the file; a copy didn't work for me until I symlinked it.