The best way to predict the future is to implement it. | |
Alan Kay |
Of course, there are java classes that cannot be emulated in the browser. For example, the class java.util.File: there is no way in a browser to read and write a file in the filesystem, so the classes related to filesystem like java.lang.File, java.lang.FileOutputStream are not supported by Java2Script. The same way, it is not possible to use multiple threads or processes in a javascript program and so classes related to threads like java.lang.Thread are not supported.
Let's see what happen when we try to use unsupported java classes in our Java2Script applications. Let's create java class with the following content:
package foo.bar; import java.io.File; public class WontWork { public static void main(String[] args) { new File("foo.txt"); } } |
Let's see if Java2Script compiled the class. Save the file, right click and choose "Edit converted *.js" option from the context menu:
Clazz.declarePackage ("foo.bar"); Clazz.load (null, "foo.bar.WontWork", ["java.io.File"], function () { c$ = Clazz.declareType (foo.bar, "WontWork"); c$.main = Clazz.defineMethod (c$, "main", function (args) { new java.io.File ("foo.txt"); }, "~A"); }); |
So, as we can see in line 5 of the generated js file, the java class is translated anyway, no matter if it contains or reference a not supported java class. The compiler won't fail, but if we execute the class as a J2S application, the generated html will contain a message error like the following:
[Java2Script] Error in loading ../path/to/j2slib/java/io/File.js! |
More, if we open the html document with firefox, the following javascript error will be thrown in the Firefox error console:
Error: java.io.File is not a constructor Source File: file:///path/to/project/bin/foo/bar/WontWork.js Line: 6 |
Remember we have said that one of the main porpuses of J2S is to let the user to reuse Java codes inside web applications. So, this feature of not failing at compile time but at run time can be usefull when trying to compile an existing Java library or framework to javascript because the Java code will be compiled no matter if it contains not supported java classes. Also, generated javascript will run OK as long as the unsupported classes are not needed. But will fail when trying to load an unsupported class with a message like we have showed.
Important: Java classes referencing unsupported java classes will not fail to compile. What will fail is loading unsuported classes when the J2S application is launched in an HTML document.