Ahmed Raaj Ahmed Raaj - 8 days ago 5
Java Question

java class.forClass() vs Class declaration

I have one class Student which is

package org.ahmed;

public class Student {

public Student() {
// TODO Auto-generated constructor stub
System.out.println("Generated constructor");
}

static { // static block
System.out.println("Hello world static");
}

{ // insance block
System.out.println("Hello world non static");
}
}


and then

public class Main {

public static void main(String[] args) throws ClassNotFoundException {
Class.forName("org.ahmed.Student"); // this line causing static block execution in Student class
// Student s; // this line doesn't execute the static block.
}
}


I understand by using
Class.forClass()
we can dynamically run any
class in runtime. But I have some question in other case regarding
static block.

If I use
Class.forClass("org.ahmed.Student")
in my
main
method, then it's
executing the static block of
Student
. But if I declare
Student s
in
main
method its doesn't execute the static block. I thought
Class.forClass("ClassName")
is same as declaring class with a variable
name.

Answer

From javadoc:

Invoking Class.forName(className) method is equivalent to: Class.forName(className, true, currentLoader), where the second parameter specifies whether or not the class will be initialized.

So if you don't want to initialize the class, just call the method with initialize = false, e.g:

Class.forName("org.ahmed.Student", false, this.getClass().getClassLoader())}
Comments