2015-07-03 29 views
0

我編寫項目,在那裏使用Groovy和Java。 我有這樣的Groovy腳本在我的項目:使用GroovyShell從Java代碼運行腳本

int sum(def a, def b) { 
return (int)a + (int)b; 
} 

在我的主Java類我寫這篇文章:

public static void main(String[] args) { 
    int answer = 0; 
    String[] arguments = new String[]{"1", "2"}; 
    GroovyShell shell = new GroovyShell(); 
    try { 
     answer = (int) shell.run(new File("src/Summary.groovy"), arguments); 
     System.out.print(answer); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

但我在這行NullPointerExceptionanswer = (int) shell.run(new File("src/Summary.groovy"), arguments); 所以,我想要什麼?我想運行Main類並調用groovy腳本,它包含sum a + b函數並將此值返回給Java代碼。 我該怎麼做纔對? UPD: 完整堆棧跟蹤從主類:

Exception in thread "main" java.lang.NullPointerException 
at Main.main(Main.java:12) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:497) 
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) 

UPD2: 不正確的輸出: a:1 b:2 answer: 33 我使用這個腳本:

def sum (int a, int b) { 
print("a:" + a + " b:" + b + "\n") 
return a + b 
} 
return sum (args[0].toInteger(), args[1].toInteger()) 

和代碼的主類調用正確,但答案不正確

+0

如果你把完整的堆棧跟蹤放在一起,它會容易得多......它將使我們能夠找出哪一部分在行中爲'null'... – Codebender

+0

@Codebender我從Main類放置堆棧跟蹤,我的項目 – Giymose

+0

@Giymose,所以現在調查第140行。 – Opal

回答

1

你必須在你的腳本中調用某些東西 - 不只是提供一個函數。所以,你的腳本可能看起來像:

int sum(def a, def b) { 
    return ((int)a) + ((int)b) 
} 
return sum (args[0], args[1]) 

還有鑄造字符串爲int看起來很怪異 - 也許你想解析字符串整數或東西(例如"1".toInteger()a.toInteger()在你的情況下)。

+0

非常感謝。 我這樣做,但結果不正確。 我看到: a:1 b:2 答案:33. 看代碼在頂部 – Giymose

+0

它工作正常我的箱子 - 打印出「3」。你確定你不打印兩次結果嗎? ' a:1 b:2 過程完成退出代碼0' – defectus

+0

是的,這是我的錯誤。非常感謝您的幫助 – Giymose