當searchValue
是RegEx表達式時,我無法在來自Rhino的Java String對象上調用.replace(searchValue, newValue)
。當searchValue
不是RegEx表達式,或者在從JavaScript內部啓動的字符串上調用方法時,這可以正常工作。Rhino:如何讓Rhino評估Java字符串上的RegEx表達式?
例子:
樣品的Java對象,並返回一個字符串
public class MyTestObject {
public String returnStringValue() {
return " This is a string with spaces ";
}
}
設置犀牛的一個方法,創建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)。
謝謝,這似乎是合理的,但是因爲'.replace(val1,val2)'是從JavaScript代碼(而不是Java代碼)中調用的,所以我不知道如何解決這個問題。我試圖將returnStringValue()的返回值更改爲CharSequence,但它導致了相同的問題 – Pauline