Is this possible for use javascript to call a java method?

后端 未结 4 2067
太阳男子
太阳男子 2021-01-02 18:18

The java have a script manager that allow java calling javascript, like this:

import javax.script.*;
public class ExecuteScript {
 public static void main(St         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 19:18

    Quickly hacked together from the 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");
        }
    }
    

    Output

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

提交回复
热议问题