2016-09-27 55 views
0

我正在嘗試使用Java的腳本引擎管理器運行lodash命令。我已經將lodash-4.15.0.jar文件添加到我的類路徑中。無法使用Java的ScriptEngineManager執行lodash命令

這裏是我的代碼:

ScriptEngineManager factory = new ScriptEngineManager(); 
ScriptEngine engine = factory.getEngineByName("nashorn"); 
engine.eval("_.camelCase('[email protected] Column'))"); 

我預期的結果是:testthtColumn但是我看到下列錯誤:

Exception in thread "main" javax.script.ScriptException: ReferenceError: "_" is not defined in <eval> at line number 1 
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467) 
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:451) 
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:403) 
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399) 
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155) 
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264) 
at Tester.main(Tester.java:16) 
Caused by: <eval>:1 ReferenceError: "_" is not defined 
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57) 
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319) 
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291) 
    at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1426) 
    at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:1) 
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637) 
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494) 
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393) 
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:446) 
    ... 5 more 

由於我缺乏與一般的JavaScript的經驗我不知道如何解決這個問題。任何幫助是極大的讚賞。謝謝!

回答

0

我最終在Java中執行此操作代替獲取lodash的工作。儘管不是直接的答案,但它返回的結果與lodash的camelCase方法相同。

public String camelCaseHeaderName(String s) { 
     String result = ""; 
     boolean firstElem = false; 
     String[] words = s.split(" "); 
     for(int i = 0; i < words.length; i++) { 
      String[] finalWords = words[i].split("[^0-9a-zA-Z]+"); 
      for(int j = 0; j < finalWords.length; j++) { 
       String tmp = finalWords[j].replaceAll("[^0-9a-zA-Z]+", ""); 
       if(!firstElem) { 
        tmp = tmp.toLowerCase(); 
        firstElem = true; 
       } else { 
        tmp = WordUtils.capitalizeFully(tmp); 
       } 
       result = result.concat(tmp); 
      } 
     } 
     return result; 
    }