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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With