@kotyのブログ

PythonとかAWSとか勉強会のこととかを、田舎者SEがつづります。記事のライセンスは"CC BY"でお願いします。

Nashornを使ってみた。

JDK8 Early Access Releases に、JVM上で動くJavaScriptエンジンであるNashornが入ったみたいですね。そんな折、下記の記事を見つけたので自分も試してみました。

http://d.hatena.ne.jp/tomoTaka/20130426/1366932045

これはいいですね。サーバーとクライアントでロジックを共有できる予感がいたします。パフォーマンスはどうなんでしょう。またためしてみよう。

package com.mycompany.mypj1;

import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.junit.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

public class NashornTest {

    @Test
    public void Nashornテスト() throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("Nashorn");  // *** ここで「Nashorn」を指定
        System.out.println(String.format("*** Engine:%s", engine.getFactory().getEngineName()));
        Path path = Paths.get("src/main/resources/hello.js");  // 対象のJavaScriptファイルを指定
        Reader reader = Files.newBufferedReader(path, Charset.forName("utf8"));
        engine.put(ScriptEngine.FILENAME, path.getFileName().toString());

        //関数の定義を読み込む
        engine.eval(reader);
        //関数を呼ぶ
        Object ret = engine.eval("sayHello('社畜');");

        assertThat(ret.toString(), is("ハロー社畜!"));

    }
}

下記のスクリプトを、hello.jsとしてsrc/main/resources/に配置。

function sayHello(name){
    return "ハロー" + name + "!";
}