Home > Java > javaTutorial > How to call js method in java

How to call js method in java

王林
Release: 2020-02-01 21:06:12
Original
3896 people have browsed it

How to call js method in java

js方法如下:

function add(a,b){
	return a + b + number;	
}
Copy after login

调用方法如下:(免费学习视频教程分享:java视频教程

package com.cgnb.dataqualitymng;
 
import java.io.FileReader;
import java.util.Scanner;
 
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
 
public class ExecuJs {
	public static void main(String[] args) throws Exception {
 
		// 获取JS执行引擎
		ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");
		// 获取变量
		Bindings bindings = se.createBindings();
		bindings.put("number", 3);
		se.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
		Scanner sc = new Scanner(System.in);
		while (sc.hasNextInt()) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			System.out.println("输入的参数【" + a + "】 + 【" + b + "】");
			se.eval(new FileReader("D:\\desk\\test.js"));
			// 是否可调用
			if (se instanceof Invocable) {
				Invocable in = (Invocable) se;
				Integer result = (Integer) in.invokeFunction("add", a, b);
				System.out.println("获得的结果:" + result);
				
			}
 
		}
 
	}
}
Copy after login

调用结果如图:

How to call js method in java

相关文章教程推荐:java入门教程

The above is the detailed content of How to call js method in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template