大家好,我尝试过各种不同的方法来在Java中运行groovy并没有运气,已经阅读了一些文档,但目前还不清楚。
任何人都可能知道如何运行这种常规操作吗?
package com.test.dev.search;
public class SearchQueryBase implements SearchQuery {
public QueryString getMatterQuery( SearchFilter filter ) {
String[] terms = filter.getSearchTerm().toLowerCase().split( " " );
...
...
...
}
}
这是一个.groovy文件(上面的文件),我尝试了以下操作来运行它,但是没有运气。
这是我要在其中运行上述Groovy并执行getMatterQuery()
以查看Java main的输出的Java类。
public static void main(String args[]) throws CGException {
String TEMPLATE_PACKAGE_PREFIX = "<path_to_groovy_file.";
String templateFileName = TEMPLATE_PACKAGE_PREFIX + "SearchQueryBase";
SearchFilter test = null;
Binding binding = new Binding();
binding.setVariable("filter", test);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate(templateFileName);
System.out.println("Finish");
}
编辑#1
这是我运行它时遇到的错误;
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: Common for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
答案 0 :(得分:1)
1。
GroovyShell.evaluate(java.lang.String scriptText)
接受字符串作为常规文本(内容),而您尝试使用文件名来代替它。使用shell.evaluate( new File(templateFileName) )
2。
您可以继续使用shell.evaluate( new File(...) )
,但仅将getMatterQuery()
方法的内容保留在groovy文件中:
String[] terms = filter.getSearchTerm().toLowerCase().split( " " );
...
...
...
所以您将拥有普通的脚本,并且您的代码应该可以工作
3。
如果您想将Groovy保留为一个类,并使用参数从此类中调用方法getMatterQuery()
,则您的Java代码应如下所示:
import groovy.lang.*;
...
public static void main(String[]s)throws Exception{
GroovyClassLoader cl=new GroovyClassLoader();
//path to base folder where groovy classes located
cl.addClasspath(path_to_groovy_root);
//the groovy file with SearchQueryBase.groovy
//must be located in "com/test/dev/search" subfolder under path_to_groovy_root
Class c = cl.loadClass("com.test.dev.search.SearchQueryBase");
SearchQuery o = (SearchQuery) c.newInstance();
System.out.println( o.getMatterQuery(test) );
}