关闭

java中使用javascript Nashorn引擎

274人阅读 评论(0) 收藏 举报



在混合语言编程中,就是语言与语言间的交互。

1   在java中调用javascript 函数


javascript文件:nashorn1.js

//定义javascript函数
var fun1 = function(name) {
    print('Hi there from Javascript, ' + name);
    return "greetings from javascript";
};

var fun2 = function (object) {
    print("JS Class Definition: " + Object.prototype.toString.call(object));
};

print("String :"+Object.prototype.toString("aaaa"))

java文件: nashorn1.java

<span style="white-space:pre">	</span>//获取nashorn javascript 运行时环境
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        //加载并执行javascript脚本
        engine.eval(new FileReader("res/nashorn1.js"));
        
        Invocable invocable = (Invocable) engine;
        //调用javascript函数
        Object result = invocable.invokeFunction("fun1", "Peter Parker");
        System.out.println(result);
        System.out.println(result.getClass());
        
        invocable.invokeFunction("fun2", new Date());
        invocable.invokeFunction("fun2", LocalDateTime.now());
        invocable.invokeFunction("fun2", new Person());

参考:

Object.prototype.toString()函数

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString


2   在javascript调用java静态成员函数


javascript 脚本:nashorn2.js

//在javascript中调用java静态类以及静态方法
var Nashorn2 = Java.type('com.winterbe.java8.samples.nashorn.Nashorn2');
//调用静态方法
var result = Nashorn2.fun('John Doe');
print('\n' + result);

Nashorn2.fun2(123);
Nashorn2.fun2(49.99);
Nashorn2.fun2(true);
Nashorn2.fun2("hi there")
Nashorn2.fun2(String("bam"))
print('\n')
Nashorn2.fun2(new Number(23));
Nashorn2.fun2(new Date());
Nashorn2.fun2(new RegExp());
Nashorn2.fun2({foo: 'bar'});


print('passing object hash:');
Nashorn2.fun3({
    foo: 'bar',
    bar: 'foo'
});


print('passing custom person object:');

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.getFullName = function() {
        return this.firstName + " " + this.lastName;
    }
}

var person1 = new Person("Peter", "Parker");
Nashorn2.fun3(person1);
Nashorn2.fun4(person1);

java 文件:nashorn2.java

public class Nashorn2 {

    public static String fun(String name) {
        System.out.format("Hi there from Java, %s", name);
        return "greetings from java";
    }

    public static void fun2(Object object) {
        System.out.println(object.getClass());
    }
    //ScriptObjectMirror表示对javascript对象的映射
    //返回所有属性的键,包括不可迭代的属性
    public static void fun3(ScriptObjectMirror mirror) {
        System.out.println(mirror.getClassName() + ": " + Arrays.toString(mirror.getOwnKeys(true)));
    }
    //调用JavaScript对象的方法 
    public static void fun4(ScriptObjectMirror person) {
        System.out.println("Full Name is: " + person.callMember("getFullName"));
    }

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval(new FileReader("res/nashorn2.js"));
    }

}
Java.type()方法参考:
https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html

ScriptObjectMirror对象:

http://cr.openjdk.java.net/~sundar/jdk.nashorn.api/8u20/javadoc/jdk/nashorn/api/scripting/ScriptObjectMirror.html


3 -在javascript中使用java对象

javascript 文件: nashorn3.js

print('------------------');
print('IntArray:');

var IntArray = Java.type('int[]');

var array = new IntArray(5);
array[0] = 5;
array[1] = 4;
array[2] = 3;
array[3] = 2;
array[4] = 1;

try {
    array[5] = 23;
} catch (e) {
    print("错误:"+e.message);
}

array[0] = "17";
print(array[0]);

array[0] = "wrong type";
print(array[0]);

array[0] = "17.3";
print(array[0]);

print('------------------');

for (var i in array) print(i);

print('------------------');

for each (var val in array) print(val);

print('------------------');
print('ArrayList:');

var ArrayList = Java.type('java.util.ArrayList');

var list = new ArrayList();
list.add('a');
list.add('b');
list.add('c');

for each (var el in list) print(el);


print('------------------');
print('HashMap:');

var HashMap = Java.type('java.util.HashMap');

var map = new HashMap();
map.put('foo', 'foo1');
map.put('bar', 'bar1');

for each(var e in map.keySet()) print(e);

for each(var e in map.values()) print(e);


print('------------------');
print('Streams:');

var list2 = new ArrayList();
list2.add("ddd2");
list2.add("aaa2");
list2.add("bbb1");
list2.add("aaa1");
list2.add("bbb3");
list2.add("ccc");
list2.add("bbb2");
list2.add("ddd1");

list2
    .stream()
    .filter(function(el) {
        return el.startsWith("aaa");
    })
    .sorted()
    .forEach(function(el) {
        print(el);
    });



print('------------------');
print('Extend:');

var Runnable = Java.type('java.lang.Runnable');
var Printer = Java.extend(Runnable, {
    run: function() {
        print('This was printed from a seperate thread.');
    }
});

var Thread = Java.type('java.lang.Thread');
new Thread(new Printer()).start();

new Thread(function() {
    print('this was printed from another thread');
}).start();


print('------------------');
print('Parameter Overload:');

var System = Java.type('java.lang.System');

System.out.println(10);
System.out["println"](11.0);
System.out["println(double)"](12);

print('------------------');
print('JavaBeans:');

var Date = Java.type('java.util.Date');
var date = new Date();
date.year += 1900;
System.out.println(date.year);

java文件:nashorn3.java

public class Nashorn3 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn3.js')");
    }

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:121950次
    • 积分:2542
    • 等级:
    • 排名:第14978名
    • 原创:120篇
    • 转载:4篇
    • 译文:21篇
    • 评论:11条
    最新评论