Java program calls JavaScript and other scripts to implement the method

Source: Internet
Author: User

public static void Main (string[] args) throws FileNotFoundException, Scriptexception, nosuchmethodexception{
ScriptEngine engine = new Scriptenginemanager (). Getenginebyname ("JavaScript");
Setting up a contextual environment
Bindings bind = Engine.createbindings ();
Bind.put ("factor", 1);
Binding context, scope is current engine scope
Engine.setbindings (Bind, Scriptcontext.engine_scope);
Receive parameter input
Scanner Scanner = new Scanner (system.in);
while (Scanner.hasnextint ()) {
int first = Scanner.nextint ();
int second = Scanner.nextint ();
SYSTEM.OUT.PRINTLN ("Receive parameter:" +first+ "," +second ");
Engine Execution Script
Engine.eval (New FileReader ("C:/modal.js"));
Determines whether an executable
if (engine instanceof invocable) {
Invocable in = (invocable) engine;
Double result = (double) in.invokefunction ("formula", First,second);
System.out.println ("Execution result:" +result);
}

}

}

The contents of the Modal.js script under C disk are as follows:

function formula (value1,value2) {
return value1+value2-factor;
}

Java program calls JavaScript and other scripts to implement the method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.