本文介绍了Groovy类加载器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在eclipse环境中使用groovy和java来开发UI应用程序。我想在我的代码中使用groovy类加载器,所以我使用了以这种方式获取Groovy类加载器的传统方式:

  def str = new File(C:/myGroovyFile.groovy)。getText()
def myclass = getClass();
println myclass //在这里面临问题
ClassLoader parent = myclass.getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
类groovyClass = loader.parseClass(s​​tr);

这里我遇到的问题是在eclipse环境中调用getClass()时没有返回GroovyCOnsole脚本,而不是返回java.lang.class,在调用getClassLoader()时返回null。



我想要获得groovy控制台脚本的getClass (),这反过来可以用于动态加载位于C:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

PS:我试图将这段代码放在一个名为initialize()的方法中。只要此代码位于主类中,它就可以工作,但是当我将上述代码放在自定义用户定义的函数中时,它不起作用。为什么会这样?

解决方案

编辑









由于您可以从main获得正确的类加载器,您不能将加载器引用传递给initialize()作为方法param ?

我遇到了类似Groovlets的问题,类加载器根据调用的上下文(即脚本或类作用域)而显示不同。对我来说,解决方案是采用脚本范围类加载器,并将加载器ref传递给类范围应用程序。



Groovy用户列表涵盖了groovy中不同时间的类加载主题;显然是Groovy所有事情的一个很好的资源; - )


I am using both groovy and java within the eclipse environment to develop a UI application. I want to use groovy class loader within my code, So I've used the conventional way of getting hold of Groovy Class loader this way:

def str = new File("C:/myGroovyFile.groovy").getText()
def myclass = getClass();
println myclass //facing issue here
ClassLoader parent = myclass.getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(str);

Here the problem I am facing is that the getClass() when invoked in the eclipse environment is not returning the GroovyCOnsole script rather it is returning the java.lang.class on which getClassLoader() when invoked returns a null.

I want to get hold of groovy console script for getClass() which in turn can be useful to dynamically load my groovy file located at C:\

Please tell me how can I solve this issue.

PS: I am trying to place this code within a method called initialize(). As long as this code is within the main class, it works but when I enclose the above code within a custom user defined function it doesn't work. Why is it so?

解决方案

Edit
http://groovy.codehaus.org/Embedding+Groovy
http://groovy.codehaus.org/Class+Loading
http://groovy.codehaus.org/Influencing+class+loading+at+runtime
http://groovy.codehaus.org/api/groovy/lang/GroovyClassLoader.html

Since you are able to get correct class loader from main, can you not pass the loader reference to initialize() as a method param?

I confronted a similar issue with Groovlets, where class loader appears to differ depending on context in which it is called (i.e. script or class scope). Solution for me was to take script scope class loader and pass the loader ref to class scoped application.

Groovy user list has covered the topic of class loading in groovy at various times; obviously a great resource for all things Groovy ;--)
http://groovy.329449.n5.nabble.com/

这篇关于Groovy类加载器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:57