动态调用动态语言,第 2 部分: 在运行时寻找、执行和修改脚本
2009-11-19 00:00:00 来源:WEB开发网Java 脚本编程 API 正好能够满足这种需求。这个应用程序由一个 ScriptMortgageQualifier 类组成,这个类负责判断打算购买某一资产的贷款人是否符合给定的抵押贷款产品的条件。清单 1 给出这个类。
清单 1. ScriptMortgageQualifier 类
// Imports and Javadoc not shown.
public class ScriptMortgageQualifier {
private ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
public MortgageQualificationResult qualifyMortgage(
Borrower borrower,
Property property,
Loan loan,
File mortgageRulesFile
) throws FileNotFoundException, IllegalArgumentException, ScriptException
{
ScriptEngine scriptEngine = getEngineForFile(mortgageRulesFile);
if (scriptEngine == null) {
throw new IllegalArgumentException(
"No script engine on classpath to handle file: " + mortgageRulesFile
);
}
// Make params accessible to scripts by adding to engine's context.
scriptEngine.put("borrower", borrower);
scriptEngine.put("property", property);
scriptEngine.put("loan", loan);
// Make return-value object available to scripts.
MortgageQualificationResult scriptResult = new MortgageQualificationResult();
scriptEngine.put("result", scriptResult);
// Add an object scripts can call to exit early from processing.
scriptEngine.put("scriptExit", new ScriptEarlyExit());
try {
scriptEngine.eval(new FileReader(mortgageRulesFile));
} catch (ScriptException se) {
// Re-throw exception unless it's our early-exit exception.
if (se.getMessage() == null ||
!se.getMessage().contains("ScriptEarlyExitException")
) {
throw se;
}
// Set script result message if early-exit exception embedded.
Throwable t = se.getCause();
while (t != null) {
if (t instanceof ScriptEarlyExitException) {
scriptResult.setMessage(t.getMessage());
break;
}
t = t.getCause();
}
}
return scriptResult;
}
/** Returns a script engine based on the extension of the given file. */
private ScriptEngine getEngineForFile(File f) {
String fileExtension = getFileExtension(f);
return scriptEngineManager.getEngineByExtension(fileExtension);
}
/** Returns the file's extension, or "" if the file has no extension */
private String getFileExtension(File file) {
String scriptName = file.getName();
int dotIndex = scriptName.lastIndexOf('.');
if (dotIndex != -1) {
return scriptName.substring(dotIndex + 1);
} else {
return "";
}
}
/** Internal exception so ScriptEarlyExit.exit can exit scripts early */
private static class ScriptEarlyExitException extends Exception {
public ScriptEarlyExitException(String msg) {
super(msg);
}
}
/** Object passed to all scripts so they can indicate an early exit. */
private static class ScriptEarlyExit {
public void noMessage() throws ScriptEarlyExitException {
throw new ScriptEarlyExitException(null);
}
public void withMessage(String msg) throws ScriptEarlyExitException {
throw new ScriptEarlyExitException(msg);
}
}
}
更多精彩
赞助商链接