Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassLoader confusion

I have seen several places that "Class.getClassLoader() returns the ClassLoader used to load that particular class", and therefore, I am stumped by the results of the following example:


package test;

import java.lang.*;

public class ClassLoaders { 
    public static void main(String[] args) throws java.lang.ClassNotFoundException{
      MyClassLoader mcl = new MyClassLoader();
      Class clazz = mcl.loadClass("test.FooBar");
      System.out.println(clazz.getClassLoader() == mcl); // prints false
      System.out.println(clazz.getClassLoader()); // prints e.g. sun.misc.Launcher$AppClassLoader@553f5d07
    }
}

class FooBar { }

class MyClassLoader extends ClassLoader { }

Shouldn't the statement clazz.getClassLoader() == mcl return true? Can someone explain what I am missing here?

Thanks.

like image 724
Eyvind Avatar asked Apr 03 '09 11:04

Eyvind


People also ask

What is the function of ClassLoader?

The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren't loaded into memory all at once, but when required by an application.

What do you mean by ClassLoader?

A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class.

What is ClassLoader and types?

ClassLoader is hierarchical in loading a class into memory. Whenever a request is raised to load a class, it delegates it to the parent classloader. This is how uniqueness is maintained in the runtime environment. If the parent class loader doesn't find the class then the class loader itself tries to load the class.

When would you use a custom ClassLoader?

Custom class loaders You might want to write your own class loader so that you can load classes from an alternate repository, partition user code, or unload classes.


1 Answers

Whenever you create your own classloader it will be attached in a tree-like hierarchy of classloaders. To load a class a classloader first delegates the loading to its parent. Only once all the parents didn't find the class the loader that was first asked to load a class will try to load it.

In your specific case the loading is delegated to the parent classloader. Although you ask you MyClassLoader to load it, it is the parent that does the loading. In this case it is the AppClassLoader.

like image 184
paweloque Avatar answered Sep 20 '22 23:09

paweloque