JavaPoly.js让Java代码无需JVM在浏览器中运行

16-05-09 banq
         

JavaPoly.js是一个能够在浏览器中支持原生JVM应用的Javascript库包,能够导入你原有的Java代码,然后从Javascript直接调用java代码。即使你的电脑上没有安装任何Java环境,无需使用applet,可以在浏览器中直接嵌入你的Java代码并运行。

<!-- Include the Polyfill -->
< script src = "javapoly.js" >

<!-- Write your Java code -->

  package com.demo;
  import com.javapoly.dom.Window;

  public class HelloWorld
  {
    public static void sayHello()
    {
      Window.alert("Hello World, from Java!");
    }
  }


<!--从Javascript调用Java代码 -->
< script type=“text/javascript”>
  com.demo.HelloWorld.sayHello();
< /script >


<p>

指出java库包jar的导入:

<!-- Include the Polyfill -->
< script src = "javapoly.js">

<!-- Include your favorite Java libraries (jar files) -->
< script type ="text/java" src ="jimboxutilities.jar">
< script type="text/java" src ="guava.jar">
< script type="text/java" src ="apache-commons.jar">

<!-- Or, include individual .class files -->
< script type = "text/java" src ="com/yourpackage/Foo.class"></script >
< script type = "text/java" src ="com/yourpackage/Noise.class"></script >

<!-- Or just include the source directly -->
< script type ="text/java" src ="com/yourpackage/Bar.java"></script >
< script type ="text/java" src ="com/yourpackage/Girls.java"></script >
<p>

导入的库包或class就可以通过完整包名以Javascript方式直接调用:

< script type=“text/javascript”>
  com.yourpackage.Foo.doSomething();
  com.yourpackage.Noise.doSomethingElse();
</script >
<p>

更牛逼的是还支持异步调用,Javascript是单线程的,而Java应用可以是多线程,为了防止浏览器UI线程因为Javascript代码中可能因为需要等待返回结果而堵塞,UI线程可以异步调用JVM中Java代码,Javascript调用Java代码总是返回一个promise(es6):

var promise = com.mypackage.MyClass.getSomeValue();
promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});
<p>

项目:

JavaPoly.js — Java(script) in the Browser

[该贴被banq于2016-05-09 12:55修改过]

         

1