我有一个很棒的脚本createWidget.groovy:
import com.example.widget
Widget w = new Widget()当我像这样运行这个脚本时,它运行得很好:
$ groovy -cp /path/to/widget.jar createWidget.groovy但是,我希望在脚本中硬编码类路径,这样用户就不需要知道它在哪里,所以我修改了createWidget.groovy,如下所示(这是在groovy中修改类路径的一种方法):
this.getClass().classLoader.rootLoader.addURL(new File("/path/to/widget.jar").toURL())
import com.example.widget
Widget w = new Widget()但这总是会失败,并在导入时出现运行时错误:unable to resolve class com.example.widget。
这看起来有点不合常理,我想你不能在导入之前弄乱rootLoader,或者是其他什么东西?
发布于 2014-06-24 06:21:22
// Use the groovy script's classLoader to add the jar file at runtime.
this.class.classLoader.rootLoader.addURL(new URL("/path/to/widget.jar"));
// Note: if widget.jar file is located in your local machine, use following:
// def localFile = new File("/path/tolocal/widget.jar");
// this.class.classLoader.rootLoader.addURL(localFile.toURI().toURL());
// Then, use Class.forName to load the class.
def cls = Class.forName("com.example.widget").newInstance();发布于 2013-04-26 14:08:48
如果我理解这个问题,那么您要求的是一个可以交付给用户的独立单元。
在JVM上使用'jar‘的基础知识就可以做到这一点。
例如,this project玩一个叫做“战争-O”的简单游戏。用户可以使用以下命令运行它:
java -jar warO.jar [args]该技术包括:(a)将Groovy编译为类文件,(b)在jar中包含所有必需的jar(包括groovy- all )。此外,jar必须在清单中指定“主”入口点(这将是脚本的修改版本)。
War-O项目使用Gradle (请参阅build file here),但即使使用Ant、Maven等,该原则也适用。
jar.archiveName 'warO.jar'
jar.manifest {
attributes 'Main-Class' : 'net.codetojoy.waro.Main'
attributes 'Class-Path' : 'jars/groovy-all-1.6.4.jar jars/guava-collections-r03.jar jars/guava-base-r03.jar'
}发布于 2016-08-23 18:40:11
另一种方法是编写java代码,以便从jar文件中加载类,然后按照groovy的要求修改代码。
import java.net.URL;
import java.net.URLClassLoader;
import java.lang.reflect.Method;
public class JarFileLoader
{
public static void main (def args)
{
try
{
URLClassLoader cl = new URLClassLoader (new URL("jar:file:///path/to/widget.jar!/"));
System.out.println ("Attempting...");
Class beanClass = cl.loadClass ("com.example.widget.WidgetClass");
Object dog = beanClass.newInstance();
Method method = beanClass.getDeclaredMethod ("setBean", String.class);
method.invoke (dog, "Who let the dog out");
method = beanClass.getDeclaredMethod("getBean", null);
Object retObj = method.invoke (dog, null);
String retVal = (String)retObj;
System.out.println(retVal);
System.out.println("Success!");
}
catch (Exception ex)
{
System.out.println ("Failed.");
ex.printStackTrace ();
}
}
}https://stackoverflow.com/questions/16219805
复制相似问题