简体   繁体   中英

How does GroovyClassLoader/ClassLoader work?

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.

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.

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.

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:

  • Groovy code needs a suitable environment
  • You eventually want to get rid of the script (and all its classes)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM