当searchValue
是正则表达式时,我无法从 Rhino 调用 Java String 对象上的.replace(searchValue, newValue)
。当searchValue
不是正则表达式时,或者当该方法在从 JavaScript 中启动的字符串上调用时,这工作正常。
例:
示例 Java 对象和返回字符串的方法
public class MyTestObject {
public String returnStringValue() {
return " This is a string with spaces ";
}
}
设置Rhino,创建Java对象
import java.io.FileNotFoundException;
import javax.script.*;
public class TestRhino{
public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
// Create my Java Object
MyTestObject testObject = new MyTestObject();
// Initiate the JavaScript engine
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Compilable compEngine = (Compilable)engine;
// evaluate my JavaScript file; add my Java object to it
engine.eval(new java.io.FileReader("MyJavaScriptFile.js"));
engine.put("testObject", testObject); // this adds my Java Object to Rhino
// Invoke my javaScript function
Invocable inv = (Invocable) engine;
Object returnVal = inv.invokeFunction("testFunction");
// print out the result
System.out.println(returnVal); // should print "ThisisaString" to the console
}
}
我的JavaScript函数(此代码不能以任何方式修改)。
function testFunction() {
let myString = testObject.returnStringValue();
return myString.replace(/s/g,""); // Error!
}
这会引发错误The choice of Java constructor replace matching JavaScript argument types (function,string) is ambiguous; candidate constructors are: class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence)
。
但是,当我的 JavaScript 函数修改如下时,Rhino 返回预期值,并且不会抛出任何错误。
function testFunction() {
let myString = testObject.returnStringValue();
return myString.replace("T", "P"); // Phis is a string with spaces
}
以下 JavaScript 函数在使用 Rhino 调用时也有效。
function testFunction() {
return " This is a string with spaces ".replace(/s/g,""); // Thisisastringwithspaces
}
我正在寻找一种在不修改 JavaScript 代码的情况下使上述工作的方法。我只能修改Java代码。
注意:这适用于 Nashorn(从 Java1.8 开始的默认 JavaScript 引擎),但是我必须使用 Rhino(默认的 javaScript 引擎直到 Java 1.7)。
我的猜测是Java代码调用
replace(null, null);
方法,因此不知道,是否应该执行 -
replace(char oldChar, char newChar);
或
replace(CharSequence target, CharSequence replacement);
将 Java 调用中的参数转换为:
replace((CharSequence) null, (CharSequence) null);