Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GroovyClassLoader/ClassLoader work?

Tags:

java

groovy

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.

like image 321
Alexander Suraphel Avatar asked Dec 19 '22 04:12

Alexander Suraphel


1 Answers

Class loaders work in a vertical hierarchy manner, in fact in java there are three built in class loaders in this hierarchy:

class loader 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.

enter image description here

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.

like image 79
dsharew Avatar answered Dec 28 '22 22:12

dsharew