Reputation: 10613
I'm seeing code like
GroovyClassLoader cLoader = new GroovyClassLoader(this.class.getClassLoader())
Followed by something like:
cLoader.loadClass([class name])
I'm interested in what I should know about the GroovyClassLoader
class and what the purpose of this.class.getClassLoader()
is.
Upvotes: 4
Views: 10413
Reputation: 1220
As per documentation, this.class.ClassLoader()
parameter passed to the constructor is then taken as the created GroovyClassLoader
's parent (instead of using the current Thread's context Class loader as parent - the default behavior).
I'm no expert in class loading, but AFAIK the classloader's parent is first called in search for a given class.
As for what should be known about it, I can't tell you any more than is available in the documentation.
Upvotes: 1
Reputation: 10665
Class loaders work in a vertical hierarchy manner, in fact in java there are three built in class loaders in this hierarchy:
So when you pass this.class.getClassLoader(
) to the constructor you are creating a classloader whose parent is the classloader which loaded the current class, which will give you this kind classloader hierarchy.
Why creating a classloader this way?, why not get the built-in ones? that is upto you.
But one fact to remind here is classloaders load classes in a top down fashion. A classloader asks its parent to load a class, if the parent cant find the class it loads the class by itself ( notice the call is recuring) and another fact is classloaders have a cache, loaded classes are cached for sometime.
So I usually use Thread.currentThread.getClassLoader()
( which I believe is similar to urs) because this gives me the loader which loaded the current running thread and I believe it is near to my other classes and the hope is it might have cached the class I am requesting.
Upvotes: 8
Reputation: 328594
Groovy is a scripting language and as such, you'll find yourself in a lot of places where you're loading a Groovy script from a file and want to execute it. There are two problems here:
The GroovyClassLoader
will make sure that scripts (which are loaded while it's active) will work. And when it is garbage collected, it will make sure that all resources can be GC'd as well (otherwise, you would eventually run into problems if the script on disk changed and you wanted to reload it or you would run out memory, etc.)
Groovy code needs access to normal Java classes, that's why you have to give it a parent classloader. The Groovy classloader will ask the parent for anything that it doesn't know itself.
Upvotes: 3