I want to create custom class loader. But I am confused with loadClass(), does this method loads the specified class into memory?
If yes then why does the static block of the specified class is not invoked?
//main class
package custom_class_loader1;
public class Custom_class_loader1 {
public static void main(String[] args) {
try{
CustomClassLoader c=new CustomClassLoader();
开发者_StackOverflow Class c1= c.loadClass("custom_class_loader1.ABC");/**does this load ABC class into memory?**/
}catch(Exception e)
{
System.out.println(e);
}
}
}
When you load a class it doesn't initalise it until it is used by default.
Invoking this method is equivalent to invoking loadClass(name, false);
Here false
means don't resolve the class.
One way to control this is to use the Class.forName()
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
ClassLoader cl = new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader());
System.out.println("unresolved Test");
cl.loadClass("Test");
// or
Class.forName("Test", false, cl);
System.out.println("\ninitialise Test");
Class.forName("Test", true, cl);
}
}
class Test {
static {
System.out.println("Loaded Test class");
}
}
prints
unresolved Test
initialise Test
Loaded Test class
Where else would it load it? loadClass
returns an object of type Class<?>
that represents the class just loaded.
精彩评论