我尝试执行这个简单的短脚本来测试nashorn:
basedir="/cassandara2/cassandra"
ba="/cassandara2/cassandra/lib/ST4-4.0.8.jar";
lib = "";
lib += ' <root url="jar://' + ba.replace(basedir, "$PROJECT_DIR");
print(lib);
它工作得很完美,但当我在“$PROJECT_DIR”==>之后添加sign $时“$PROJECT_DIR $”,我收到此错误:
> java.lang.StringIndexOutOfBoundsException: String index out of range:
> 13 at java.lang.String.charAt(String.java:646) at
> jdk.nashorn.internal.objects.NativeRegExp.appendReplacement(NativeRegExp.java:738)
> at
> jdk.nashorn.internal.objects.NativeRegExp.replace(NativeRegExp.java:674)
> at
>
> jdk.nashorn.internal.objects.NativeString.replace(NativeString.java:763)
> bla...
这个代码是jdk 8 nashorn(我使用的是jdk8 u45)的错误:
public static void main(String[] args) {
try {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
Object eval = engine.eval("load(\"" + "script/demo.js" + "\");");
System.out.println(eval);
} catch (Exception ex) {
ex.printStackTrace();
}
}
解决方法:
Bug提交.替换字符串末尾的https://bugs.openjdk.java.net/browse/JDK-8081608 $导致索引超出范围错误
js> "string".replace("i", "$");
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
jjs> "string".replace("i", "$");
str$ng