Lei Feng pushed to Leifeng Tower, Java implements Javascript.

Source: Internet
Author: User

Recently encountered such a problem, how to let the user in the software to customize the function.

For example, using Java to do a small monitoring system, user A hope that the CPU more than 90% when the alarm, B users want to memory more than 90% when the alarm, C users want to CPU more than 90% or memory more than 80% when the alarm, D users want the CPU more than 60% and the remaining less than 10% hard disk When you call the police ...

The programmer's power is limited, but the user's desire is not dire. To develop the pursuit of demand, such as Baoxinjiuhuo, may wish to let users define their own alarm rules.

We certainly don't need to develop a scripting language for this, and I think JavaScript is a good language. We take a single-input single-output function as an example of how to use Lei Feng to tear down Leifeng pagoda ... No, use Java to parse JavaScript.

First we create a new Java project (see the complete code at the end).

Then create a new JavaScript parser:

New Scriptenginemanager (); ScriptEngine engine = Manager.getenginebyname ("javascript");

To load our script:

The script looks like this:

function (x) {    return x+1;};  

Load it:

String Js_code = readtostring ("Scripts/user_define.js");

Then try to process:

Try {    engine.put ("Udfun", Engine.eval (Js_code));    for (int i = 1; i <; + +i) {engine.put ("Val", I); System.out.printf ("f (%d) =%f\n", I,engine.eval ("Udfun (Val);" Catch (Scriptexception e) {e.printstacktrace ();}       

You can see that we first used a engine.put ("Udfun", Engine.eval (Js_code)); Load function, so as to avoid repeated parsing functions, and then constantly put the values into the JS engine, and finally output the corresponding results.

You can load different configurations as long as you modify the appropriate JavaScript scripts.

Most of the software is uncertain, and the frequency of execution is not particularly high, the performance requirements are not high places can be left a hole in this way.

Attach the full Java code:

1  Packagejavascriptevaltest;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 Importjava.io.FileNotFoundException;6 Importjava.io.IOException;7 Importjava.io.UnsupportedEncodingException;8 ImportJavax.script.ScriptEngine;9 ImportJavax.script.ScriptEngineManager;Ten Importjavax.script.ScriptException; One  A  Public classJavascriptevaltest { -  -      Public Static voidMain (string[] args) { theScriptenginemanager Manager =NewScriptenginemanager (); -ScriptEngine engine = Manager.getenginebyname ("javascript"); -          -String Js_code = readtostring ("Scripts/user_define.js"); +         Try { -Engine.put ("Udfun", Engine.eval (Js_code)); +              for(inti = 1; I < 10; ++i) { AEngine.put ("Val", i); atSystem.out.printf ("f (%d) =%f\n", I,engine.eval ("Udfun (Val);")); -             } -}Catch(scriptexception e) { - e.printstacktrace (); -         } -     } in  -      Public Staticstring readtostring (String fileName) { toString encoding = "Iso-8859-1"; +File File =NewFile (fileName); -Long filelength =file.length (); the         byte[] Filecontent =New byte[Filelength.intvalue ()]; *         Try { $FileInputStream in =Newfileinputstream (file);Panax Notoginseng In.read (filecontent); - in.close (); the}Catch(FileNotFoundException e) { + e.printstacktrace (); A}Catch(IOException e) { the e.printstacktrace (); +         } -         Try { $             return NewString (filecontent, encoding); $}Catch(unsupportedencodingexception e) { -System.err.println ("The OS does not a support" +encoding); - e.printstacktrace (); the             return NULL; -         }Wuyi     } the  -}
View Code

JavaScript code on top, slightly.

Lei Feng pushed to Leifeng Tower, Java implements Javascript.

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.