行。 ScriptEngine.eval(String string)
完整地评估字符串,ScriptEngine.eval(Reader reader)
评估整个Reader
的输入。
因此,如果我有一个文件,我可以打开一个FileInputStream,围绕它包装一个Reader,然后调用scriptEngine.eval(reader)
。
如果我有一个完整的语句作为字符串,我可以调用scriptEngine.eval(string)
。
如果我需要实现交互式解释器,该怎么办?我有一个用户在多行语句中交互式输入,例如
function f() {
return 3;
}
如果我逐行读取输入,并使用eval()
的字符串形式,我最终会将其传递给不完整的语句,例如: function f() {
并收到错误。
如果我传入一个阅读器,ScriptEngine
将一直等到输入完成,并且它不是交互式的。
帮助!
只是为了澄清:这里的问题是我只能传递ScriptEngine.eval()
完整的语句,而作为ScriptEngine的客户,我不知道什么时候输入行是完整的,没有ScriptEngine本身的帮助。
Rhino的交互式shell使用Rhino的Context.stringIsCompilableUnit()
(请参阅LXR for usage和implementation)。
答案 0 :(得分:4)
我实现了一些适用于Java SE 6 Rhino(Javascript)和Jython 1.5.2(Python)的东西,使用类似于Rhino的交互式shell的相当简单的方法(请参阅我在问题末尾的评论):
想要发生的事情是:
这是我写的一个帮助类,它实现了我的方法:
import java.lang.reflect.Method;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class ScriptEngineInterpreter
{
private static final boolean DEBUG = false;
final private ScriptEngine engine;
final private Bindings bindings;
final private StringBuilder sb;
private int lineNumber;
private int pendingLineCount;
private boolean expectingMoreInput;
/**
* @param engine ScriptingEngine to use in this interpreter
* @param bindings Bindings to use in this interpreter
*/
public ScriptEngineInterpreter(ScriptEngine engine, Bindings bindings)
{
this.engine = engine;
this.bindings = bindings;
this.sb = new StringBuilder();
this.lineNumber = 0;
reset();
}
/** @return ScriptEngine used by this interpreter */
public ScriptEngine getEngine() { return this.engine; }
protected void reset() {
this.sb.setLength(0);
this.pendingLineCount = 0;
setExpectingMoreInput(false);
}
/** @return whether the interpreter is ready for a brand new statement. */
public boolean isReady() { return this.sb.length() == 0; }
/**
* @return whether the interpreter expects more input
*
* A true value means there is definitely more input needed.
* A false value means no more input is needed, but it may not yet
* be appropriate to evaluate all the pending lines.
* (there's some ambiguity depending on the language)
*/
public boolean isExpectingMoreInput() { return this.expectingMoreInput; }
protected void setExpectingMoreInput(boolean b) { this.expectingMoreInput = b; }
/**
* @return number of lines pending execution
*/
protected int getPendingLineCount() { return this.pendingLineCount; }
/**
* @param lineIsEmpty whether the last line is empty
* @return whether we should evaluate the pending input
* The default behavior is to evaluate if we only have one line of input,
* or if the user enters a blank line.
* This behavior should be overridden where appropriate.
*/
protected boolean shouldEvaluatePendingInput(boolean lineIsEmpty)
{
if (isExpectingMoreInput())
return false;
else
return (getPendingLineCount() == 1) || lineIsEmpty;
}
/**
* @param line line to interpret
* @return value of the line (or null if there is still pending input)
* @throws ScriptException in case of an exception
*/
public Object interpret(String line) throws ScriptException
{
++this.lineNumber;
if (line.isEmpty())
{
if (!shouldEvaluatePendingInput(true))
return null;
}
++this.pendingLineCount;
this.sb.append(line);
this.sb.append("\n");
CompiledScript cs = tryCompiling(this.sb.toString(), getPendingLineCount(), line.length());
if (cs == null)
{
return null;
}
else if (shouldEvaluatePendingInput(line.isEmpty()))
{
try
{
Object result = cs.eval(this.bindings);
return result;
}
finally
{
reset();
}
}
else
{
return null;
}
}
private CompiledScript tryCompiling(String string, int lineCount, int lastLineLength)
throws ScriptException
{
CompiledScript result = null;
try
{
Compilable c = (Compilable)this.engine;
result = c.compile(string);
}
catch (ScriptException se) {
boolean rethrow = true;
if (se.getCause() != null)
{
Integer col = columnNumber(se);
Integer line = lineNumber(se);
/* swallow the exception if it occurs at the last character
* of the input (we may need to wait for more lines)
*/
if (col != null
&& line != null
&& line.intValue() == lineCount
&& col.intValue() == lastLineLength)
{
rethrow = false;
}
else if (DEBUG)
{
String msg = se.getCause().getMessage();
System.err.println("L"+line+" C"+col+"("+lineCount+","+lastLineLength+"): "+msg);
System.err.println("in '"+string+"'");
}
}
if (rethrow)
{
reset();
throw se;
}
}
setExpectingMoreInput(result == null);
return result;
}
private Integer columnNumber(ScriptException se)
{
if (se.getColumnNumber() >= 0)
return se.getColumnNumber();
return callMethod(se.getCause(), "columnNumber", Integer.class);
}
private Integer lineNumber(ScriptException se)
{
if (se.getLineNumber() >= 0)
return se.getLineNumber();
return callMethod(se.getCause(), "lineNumber", Integer.class);
}
static private Method getMethod(Object object, String methodName)
{
try {
return object.getClass().getMethod(methodName);
}
catch (NoSuchMethodException e) {
return null;
/* gulp */
}
}
static private <T> T callMethod(Object object, String methodName, Class<T> cl) {
try {
Method m = getMethod(object, methodName);
if (m != null)
{
Object result = m.invoke(object);
return cl.cast(result);
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
答案 1 :(得分:2)
创建一个从键盘(Scanner类)读取的方法,并从多行输入创建一个完整的字符串。在空行上输入表示用户输入结束。将字符串传递给eval方法。