使用JSNI从手写的Javascript调用JAVA方法

using JSNI to call JAVA methof from handwritten Javascript

本文关键字:Javascript 调用 JAVA 方法 JSNI 使用      更新时间:2023-09-26

我有一段我写的代码,我不明白为什么它不工作

我写过:

public class MyUtility {
    public static int computeLoanInterest(int amt, float interestRate, int term) {
       return (amt*term);   
    }
    public static native void exportStaticMethod() /*-{
        $wnd.computeLoanInterest =
        $entry(@com.myapp.appname.client.MyUtility::computeLoanInterest(IFI));
    }-*/;
}

Java入口点:

       public void onModuleLoad() {
           MyUtility.exportStaticMethod();
       }

和我手写的javascript代码:

    <head>
    <script type="text/javascript" language="javascript" src="projv1/projv1.nocache.js"></script>
    <script type="text/javascript">
        function mainl(){
          var it=window.computeLoanInterest(5,2,2);
          alert(it);
        }
    </script>
    </head>
    <body onload="mainl()">
    </body>

但是我在浏览器的控制台上得到一个错误:

Uncaught TypeError: undefined不是一个函数

通过JSNI导出到JavaScript后调用更精确、更准确的函数

public static native void exportStaticMethod() /*-{
    $wnd.computeLoanInterest = $entry(@com.myapp.appname.client.MyUtility::computeLoanInterest(IFI));
    $wnd.mainl();
}-*/;

应该可以:

public static native void exportStaticMethod() /*-{
    $wnd.computeLoanInterest = function(amt, interestRate, term) {
        return ($entry(@com.myapp.appname.client.MyUtility::computeLoanInterest(IFI))(amt, interestRate, term));
    }
}-*/;