Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does classLoader load imports?

Assume, that I have class with static methods only. Will class loader load every imported class when loading class to memory? Or it will only load imports when a method from this would need access to it?

Question is whether class loader loads imports when the class is loaded to memory, or just before some methods want to use them. If it is the first option I would probably need to divide some of my Util classes, to be more specialized.

like image 425
Damian Avatar asked Dec 23 '11 19:12

Damian


People also ask

How does the ClassLoader work?

A Java Class is stored in the form of byte code in a . class file after it is compiled. The ClassLoader loads the class of the Java program into memory when it is required. The ClassLoader is hierarchical and so if there is a request to load a class, it is delegated to the parent class loader.

How do I know what ClassLoader loads a class?

To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException.

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. There are three main reasons why you might want to write your own class loader. To allow class loading from alternative repositories.

Which ClassLoader loads the files from JDK directory?

5. Which class loader loads jar files from JDK directory? Explanation: Extension loads jar files from lib/ext directory of the JRE. This gives the basic functionality available.


1 Answers

I think you can test it as follows:

package pkg1;

public class Test {

    static {
        System.out.println("Hello 111");
    }

    public static void meth() {
        System.out.println("Hello 222");
    }
}

Test 1:

package pkg2;

import pkg1.Test;

public class Tester {    

    public static void main(String... args) {                   
        Test t;       
    }    
}

That prints nothing.

Test 2:

package pkg2;

import pkg1.Test;

public class Tester {    

    public static void main(String... args) {                   
        Test.meth();        
    }

}

Prints:

Hello 111
Hello 222

So, just because you have imported a class does not mean the classloader will load the class into the memory. It loads it dynamically when it's used.

like image 52
Bhesh Gurung Avatar answered Sep 29 '22 11:09

Bhesh Gurung