Running JS__JS in Java programs

Source: Internet
Author: User
Jdk

1.6 version of the added ScriptEngine can run the JS code directly


1. Write JS code directly

Import Javax.script.ScriptEngine;
Import Javax.script.ScriptEngineManager;
Import javax.script.ScriptException; /**  * Directly call the JS code * *  
public class Scriptenginetest {
public static void Main (string[] args) {
  Scriptenginemanager manager = new Scriptenginemanager ();
  ScriptEngine engine = Manager.getenginebyname ("javascript");
     try{    

          engine.eval ("var a=3; var b=4;print (a+b); ");

         Engine.eval ("alert (\" JS alert\); ");    Unable to invoke the JS function//Error defined in the browser, throws an alert reference to an exception that does not exist
}catch (scriptexception e) {

 e.printstacktrace ();
 }
 } 
}


2. Call function

Import Java.io.FileReader; 
Import javax.script.Invocable;

 Import Javax.script.ScriptEngine;

 Import Javax.script.ScriptEngineManager;  
 /**  * java invoke and execute JS file, pass parameter, and activity return value  *   * @author Manjushri/public 

class Scriptenginetest { Public  

static void Main (string[] args) throws Exception {   
Scriptenginemanager manager = new Scriptenginemanager ();   
ScriptEngine engine = Manager.getenginebyname ("javascript");   

String jsfilename = "Expression.js";   Read JS file   

filereader reader = new FileReader (jsfilename);   Executes the specified script   
engine.eval (reader);   

if (engine instanceof invocable) {    
invocable invoke = (invocable) engine;    Call the merge method and pass in two parameters    

//c = Merge (2, 3);    

Double c = (double) invoke.invokefunction ("merge", 2, 3);    

System.out.println ("c =" + C);   
}   

Reader.close ();  

  }

JS file

Expression.js
function merge (A, b) {
c = A * b;
return C;
}




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.