这是否可以使用javascript来调用java方法?

前端之家收集整理的这篇文章主要介绍了这是否可以使用javascript来调用java方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
java有一个脚本管理器,允许 java调用 javascript,如下所示:
import javax.script.*;
public class ExecuteScript {
 public static void main(String[] args) throws Exception {
 // create a script engine manager
 ScriptEngineManager factory = new ScriptEngineManager();
 // create a JavaScript engine
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 // evaluate JavaScript code from String
 engine.eval("print('Welocme to java world')");
 }

 public static void sayHi(){
   System.out.println("hihi");
 }
}

我的问题是,如果我有一个sayHi()函数,我可以使用javascript,通过脚本引擎来调用Java函数吗?谢谢.

解决方法

从JavaDocs快速入侵.
import javax.script.*;

public class ExecuteScript {

    public static void main(String[] args) throws Exception {
        // create a Java object
        ExecuteScript es = new ExecuteScript();

        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("println('Welcome to Java world')");

        // add the Java object into the engine.
        engine.put("es",es);

        ScriptEngineFactory sef = engine.getFactory();
        String s = sef.getMethodCallSyntax("es","sayHi",new String[0]);
        // show the correct way to call the Java method
        System.out.println(s);
        engine.eval(s);
    }

    public static void sayHi(){
        System.out.println("hihi");
    }
}

产量

Welcome to Java world
es.sayHi()
hihi
Press any key to continue . . .

猜你在找的JavaScript相关文章