Problem with class loading in groovy
I am so confused with the behaviour of the following code.
def file = new File("C:/MyeclipseWorkspace/SampleGroovyProject/src/templates/apixmls/one.groovy")
println file.getText()
println getClass()
ClassLoader parent = getClass().getClassLoader()
println parent
When I run this as a groovy script, I get the required output as following
class ConsoleScript10
groovy.lang.GroovyClassLoader$InnerLoader@18b995c
Rather when I just make a simple change of encasing the script within a function and executing it, It behaves in a weird manner as follows:
For the change made,
static void foo(){
def file = new File("C:/MyeclipseWorkspace/SampleGroo开发者_如何学编程vyProject/src/templates/apixmls/one.groovy")
println file.getText()
println getClass()
ClassLoader parent = getClass().getClassLoader()
println parent
}
foo()
The above code gives me a different output as follows:
class java.lang.Class
null
Can you please tell me what's wrong with the second code snippet. I would want to implement the class loading within a function and get the required output as in code snippet 1. Please Help!
if you take a look at the final outcome using Groovy's AST browser in groovyConsole you'll see the following:
public class script1302766776488 extends groovy.lang.Script {
// ...
public static void foo() {
this.println(this.getClass())
java.lang.ClassLoader parent = this.getClass().getClassLoader()
this.println(parent)
}
// ...
as the static foo method is part of the generated script class descendant, a call to this.getClass() simply returns java.lang.Class because you are in a static method and the class of the script1302766776488 class is java.lang.Class.
if you need a reference to the current class loader just call getClassLoader() (without getClass()).
精彩评论